Swift version: 5.10
You can create an NSAttributedString
directly from HTML, including support for a wide range of formatting, using a special initializer and passing in NSAttributedString.DocumentType.html
for your document type.
For example, given the following HTML:
let html = """
<html>
<body>
<h1>Hello, world!</h1>
</body>
</html>
"""
You first need to convert that string into a Data
instance, like this:
let data = Data(html.utf8)
You can now create an NSAttributedString
from that. This is a throwing call because you might try to convert something that isn’t valid, so we’re going to use try?
and wrap it in if let
:
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
yourLabel.attributedText = attributedString
}
SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.