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 Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.
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.