Creating a big paragraph with clickable Text in SwiftUI

Starting from iOS 15 you can use AttributedString or Markdown with Text. And so you get multiline formatted text.

An example of using markdown:

Text("This text is **bold**, this is *italic*. This is a tappable link: [tap here](https://stackoverflow.com)")

The advantage of AttributedString over Markdown is that it gives you more control over formatting. For example, you can set a link color or underline color:

var string = AttributedString("")

// you can use markdown with AttributedString
let markdownText = try! AttributedString(markdown: "This is **bold** text. This is *italic* text.")

var tappableText = AttributedString(" I am tappable! ")
tappableText.link = URL(string: "https://stackoverflow.com")
tappableText.foregroundColor = .green
    
var underlinedText = AttributedString("This is underlined text.")
underlinedText.underlineStyle = Text.LineStyle(pattern: .solid, color: .red)
    
string.append(markdownText)
string.append(tappableText)
string.append(underlinedText)

Text(string)

Here is what it looks like:

formatted text

A side note: if you want your tappable text to have a different behavior from opening a URL in a browser, you can define a custom URL scheme for your app. Then you will be able to handle tap events on a link using onOpenURL(perform:) that registers a handler to invoke when the view receives a url for the scene or window the view is in.


You are pushing this version of SwiftUI beyond its current capabilities!

Something like this would more easily be done using the advanced text handling in UIKit, or by thinking outside the box and converting the text to something Like HTML.

If you MUST use SwiftUI, your best bet would probably be to layout the formatted text first onto a tappable paragraph/block, and then use gesture recognition at the block level to detect where in the block the tap took place - indirectly determining if the tap position coincided with the “tappable” text.

Update #1:

Example: To use a UITextView (which supports attributed text), you could use the UIViewRepresentable protocol to wrap the UIKit view and make it accessible from within SwiftUI. e.g. Using Paul Hudson's UIViewRepresentable example for the code...

struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeUIView(context: Context) -> UITextView {
        return UITextView()
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
}

The TextView can then be used directly within SwiftUI.

Now, while Textview gives you formatting, it does not give you the clickability you need without a lot of extra work, but a WKWebView used to render an HTML version of your text would allow you to convert the clickable text into HTML links that could be handled internal to your new SwiftUI view.

Note: The reason I say that you are pushing SwiftUI to its limits is that the current version of SwiftUI hides a lot of the configurability that is exposed in UIKit and forces you to do cartwheels to get to a solution that is often already present in UIKit.

Update #2:

Here's a clickable version that uses UITextField and a NSAttributedString:

class MyTextView: UITextView, UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL)
    
        return false
    }
}

struct SwiftUIView: UIViewRepresentable {
    @Binding var text: NSAttributedString

    func makeUIView(context: Context) -> MyTextView {
        let view = MyTextView()
        
        view.dataDetectorTypes = .link
        view.isEditable        = false
        view.isSelectable      = true
        view.delegate          = view
        
        return view
    }

    func updateUIView(_ uiView: MyTextView, context: Context) {       
        uiView.attributedText = text
    }
}

All you need to do now is convert the downloaded text into a suitable attributed string format and you have attributed formatting and clickability

Tags:

Ios

Swiftui