在SwiftUI HtmlView中点击外部链接的委托



我使用HTMLView从这个答案

但有时我有一个链接,如果我点击它会打开Safari

是否存在于SwiftUI一些委托捕捉链接与这个HTMLView?

可以将UITextViewUITextDelegate设置为UIViewRepresentableCoordinator。然后,您可以决定如何处理shouldInteractWith中的url。如果返回false,系统将不使用Safari导航到URL。

struct HTMLFormattedText: UIViewRepresentable {

let text: String

init(_ content: String) {
self.text = content
}

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

func makeUIView(context: UIViewRepresentableContext<Self>) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
return textView
}

func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<Self>) {
DispatchQueue.main.async {
if let attributeText = self.converHTML(text: text) {
uiView.attributedText = attributeText
} else {
uiView.text = ""
}
}
}

func makeCoordinator() -> Coordinator {
return Coordinator()
}

private func converHTML(text: String) -> NSAttributedString?{
guard let data = text.data(using: .utf8) else {
return nil
}

if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return attributedString
} else{
return nil
}
}
}
struct ContentView: View {
var body: some View {
HTMLFormattedText("Test<br/><a href="https://google.com">Google</a>")
}
}

相关内容

  • 没有找到相关文章

最新更新