3

I have this Custom UITextView that uses "ShouldInteractWith" method:

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

        return false
    }
}

struct ClickableText: UIViewRepresentable {
    @Binding var text: NSMutableAttributedString

    func makeUIView(context: Context) -> StudyText {
        let view = StudyText()

        view.dataDetectorTypes = .all
        view.isEditable        = false
        view.isSelectable      = true
        view.delegate          = view
        view.isUserInteractionEnabled = true

        return view
    }

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

    }
}

I have this extension to set a link to the attributed text:

extension NSMutableAttributedString {

    func apply(link: String, subString: String)  {
        if let range = self.string.range(of: subString) {
            self.apply(link: link, onRange: NSRange(range, in: self.string))
        }
    }
    private func apply(link: String, onRange: NSRange) {
        self.addAttributes([NSAttributedString.Key.link: link], range: onRange)
    }

}

And I created this layout:

struct contentView: View {
    @State text: NSMutableAttributedString = NSMutableAttributedString(string: "")

    var body: some View {
        VStack {
             ClickableText(text: self.$text)
        }
        .onAppear{

             let myText = "Click Me!"

             let attributedString = NSMutableAttributedString(string: myText)
             attributedString.apply(link: "Soeme random link", subString: myText)

             self.text = attributedString

        }
    }
}

When I click on the text view it doesn't print anything to the console and sometimes it crashes. How can I fix this?

Kevin
  • 1,103
  • 10
  • 33

1 Answers1

1

It must be provided valid URL, like

 let attributedString = NSMutableAttributedString(string: myText)
 attributedString.apply(link: "https://www.google.com", subString: myText)
Asperi
  • 228,894
  • 20
  • 464
  • 690