How to use Attributed String in SwiftUI?
How to render HTML text using swift UI ?
An Attributed String is a string that has associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.
In SwiftUI, this is realized via the ‘+’ attribute. Hence we can create different Text with associated property (like a color, tap, underline) and add them up to get resulted in Attributed Text.
(Text("This ").fontWeight(.bold) +
Text("is a atributed ").underline()+
Text("string").foregroundColor(Color.red)).frame(height: 40)
What if I have HTML string?
Apple has not added any support to render HTML as Text. To solve this Problem. We can do any of the following:
- Created Out own HTML parser and render Text.
- UIKit’s UILable already has support. Leverage UILable to render Attributed HTML String.
Option one will result in plenty of code. But option two can be achieved as follows:
Create UIViewRepresentable which takes HTML string as Parameter
struct HTMLText: UIViewRepresentable {
let html: String
func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
let label = UILabel()
DispatchQueue.main.async {
let data = Data(self.html.utf8)
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
label.attributedText = attributedString
}
}
return label
}
Now we can use it as follows:
VStack(alignment: .leading) {
HTMLText(html: "<body><h1>This is HTML String</h1></body>").frame(height: 40)
}