我使用HTMLView从这个答案
但有时我有一个链接,如果我点击它会打开Safari
是否存在于SwiftUI一些委托捕捉链接与这个HTMLView?
可以将UITextView
的UITextDelegate
设置为UIViewRepresentable
的Coordinator
。然后,您可以决定如何处理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>")
}
}