Project code:
–
Level:
There is no native solution to be able to render html in SwiftUI. I have tried several solutions, such as using the UIKit webview. Finally I will use an extension already created in this other post to use the Text component with NSAttributedString.
We are going to start by creating a struct to be able to have the html string:
struct HTMLExample {
var html: String = "<b>Example Bold</b>, <i>Italics</i> and <s>Strikethrough element</s>"
}
In order to display the html on the screen we have to transform the string to NSAttributedString. We create a new variable to return the NSAttributedString:
struct HTMLExample {
var html: String = "<b>Example Bold</b>, <i>Italics</i> and <s>Strikethrough element</s>"
var attributedHtml: NSAttributedString {
let html: String = "<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: 14\">\(self.html)</span>"
guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
return NSAttributedString(string: "")
}
do {
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf16.rawValue
]
let result = try NSAttributedString(data: data,
options: options,
documentAttributes: nil)
return result
} catch {
return NSAttributedString(string: "")
}
}
}
Basically we have to use the documentType and characterEncoding attributes of the NSAttributedString and then put the string inside an html span.
We are going to use the extension from the other post in the SwiftUI view.
struct ContentView: View {
private var object = HTMLExample()
var body: some View {
VStack {
Text(object.attributedHtml)
}
.padding()
}
}

Thank you for reading this post!
Leave a Reply