Swift version: 5.6
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
}
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
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.