Parsing HTML into NSAttributedText - How to Set Font?
To set the font when parsing HTML into NSAttributedText, use NSAttributedString
, which conveniently provides out-of-the-box HTML parsing. Here’s a snippet:
Note: Inline HTML styles will vainly attempt to upstage these settings, so show them the door: remove
font-size
andfont-family
from your HTML to allow your Swift-based font settings to steal the limelight.
Swapping Styles in Swift Versions
In the world of Swift, things evolve at a meteoric pace. The way font settings are handled across versions varies:
- For Swift 3.0 and iOS 9+ adjust
.documentType
toNSDocumentTypeDocumentAttribute
and.characterEncoding
toNSCharacterEncodingDocumentAttribute
. - Swift 2 is a whole different ballgame, swapping
.documentType
and.characterEncoding
forNSUnicodeStringEncoding
andNSHTMLTextDocumentType
.
Dressing Up HTML with Swift
Perhaps you fancy a play at custom-hatter for your HTML string? Prepend with a <style>
tag to set a default font, thus:
Post this snippet, finally achieving your ambition of becoming Swift's sartorial saint!
Customising NSMutableAttributedString
Using UIFontDescriptor
When textual traits need tweaking, UIFontDescriptor
is your trusty tool. When your text needs to boldly go where no text has gone before:
Custom content just went to a new weight class!
Enumerating and updating
When rummaging through a NSAttributedString
like a virtual Wardrobe of Narnia, use enumerateAttribute
to uncover and update fonts. Ideal when your document is as complex as a royal coronation:
Laughing in the face of complexity, one attribute at a time!
Dress rehearsal: error-proofing
As with any dressing up exercise, mistakes happen! Employ adequate error handling to prevent wardrobe malfunctions. After all, you wouldn’t want to embarrass your HTML:
Oops, looks like the HTML forgot to put on some pants!
Encapsulating in an extension
Extend the UILabel
or UITextView
to handle HTML content and the font nuances, thereby re-using the code your effort deserves:
Eureka! Efficiency just got an ally!
Dressing up Individual HTML elements
Applying inline style
Bring out the Savile Row tailoring for individual HTML tags using inline CSS within <span>
tags:
One
<span>
tag, a whole new lease on life!
Dynamic styles with string interpolation
Size matters, but keeping it dynamic matters even more! Use Swift's string interpolation to set font sizes on the fly:
It's like having a personal tailor at your fingertips!
Enumerating attributes efficiently
Computer says it needs a performance boost? Use NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
to scan large documents like a pro.
Was this article helpful?