带有 Link SwiftUI 的 NSMutableAttributedString 的 UITextView

UITextView with NSMutableAttributedString with Link SwiftUI

我有这个使用 "ShouldInteractWith" 方法的自定义 UITextView:

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

    }
}

我有这个扩展来为属性文本设置 link:

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)
    }

}

我创建了这个布局:

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

        }
    }
}

当我单击文本视图时,它不会向控制台打印任何内容,有时还会崩溃。 我该如何解决这个问题?

必须提供有效URL,喜欢

 let attributedString = NSMutableAttributedString(string: myText)
 attributedString.apply(link: "https://www.google.com", subString: myText)