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 Debug 10x faster with Proxyman. Your ultimate tool to capture HTTPs requests/ responses, natively built for iPhone and macOS. You’d be surprised how much you can learn about any system by watching what it does over the network.
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.