Last active
February 18, 2019 14:56
-
-
Save keehun/3818040ad94f4511e49f95bf1a5dbc38 to your computer and use it in GitHub Desktop.
Practical Dynamic Type, Part 3: Attributed Strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: Event Handlers | |
/// Update the sizes of all contained fonts whenever the Dynamic Type size changes. | |
@objc func uiContentSizeCategoryChanged() { | |
/// Only continue if the `UILabel` has non-nil attributed text. | |
guard let attributedString = display.attributedText else { | |
return | |
} | |
/// Get the preexisting formatted string as a `NSMutableAttributedString` since we will | |
/// modify the attributes directly in the `enumerateAttributes` loop. | |
let mutableText = NSMutableAttributedString(attributedString: attributedString) | |
/// Get the full range of the attributed text. | |
let fullTextRange = NSRange(location: 0, length: mutableText.string.count) | |
/// Enumerate over the full range of the formatted string and modify its attributes. | |
mutableText.enumerateAttributes(in: fullTextRange, options: []) { attributes, range, stop in | |
/// Get the `FontSetter` for this attributed substring | |
guard let currentFontSetter = attributes[AttributedStringView.FontSetterAttributeKey] | |
as? FontSetter else { | |
fatalError("Could not read the FontSetter being enumerated over") | |
} | |
/// Execute the `FontSetter` block to regenerate the appropriate type size. | |
let determinedFont = currentFontSetter() | |
/// Check the new type size | |
print("New font size (\(determinedFont.pointSize.description)) in range \(range)") | |
/// Update the type size of the current substring with the new, appropriate type size. | |
mutableText.addAttributes([.font : determinedFont], range: range) | |
} | |
/// Assign the new, updated formatted string to the `UILabel`. | |
display.attributedText = mutableText | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment