Please don’t make this duplicate, because I have been searching for the answer and I didn’t find it.
I have a String from API that contains HTML.
In this HTML, there’s text with the font and it’s style, a hypertext or many, and images.
I did show all of them in a UITextView but the problem is I didn’t find how to get the text with the same style and the font in the HTML.
Here’s my code:
struct HTMLFormattedText: UIViewRepresentable {
let text: String
private let textView = UITextView()
init(_ content: String) {
self.text = content
}
func makeUIView(context: UIViewRepresentableContext<Self>) -> UITextView {
textView.dataDetectorTypes = UIDataDetectorTypes.all
textView.textColor = .white
textView.backgroundColor = .clear
textView.isSelectable = true
textView.isEditable = false
textView.isUserInteractionEnabled = true
textView.translatesAutoresizingMaskIntoConstraints = false
textView.linkTextAttributes = [.foregroundColor: UIColor.white]
textView.isScrollEnabled = false
self.updateUIView(textView, context: context)
return textView
}
private func converHTML(text: String) -> NSAttributedString?{
guard let data = text.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
return nil
}
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
textView.textColor = .white
return attributedString
} else{
return nil
}
}
}