Skip to content

Instantly share code, notes, and snippets.

@keehun
Last active February 15, 2019 19:47
Show Gist options
  • Save keehun/4227bbd386ec8b10ec3f8ac25467db27 to your computer and use it in GitHub Desktop.
Save keehun/4227bbd386ec8b10ec3f8ac25467db27 to your computer and use it in GitHub Desktop.
Practical Dynamic Type, Part 3: Attributed Strings
/// `FontSetterAttributeKey` is used to keep track of the custom Font assigned to a range within
/// an `AttributedString`.
static let FontSetterAttributeKey = NSAttributedString.Key.init("FontSetterAttributeKey")
/// A `UILabel` that will render the attributed string with Dynamic Type.
lazy var display: UILabel = {
let fontSetter1: FontSetter = { UIFont.customFont(weight: .bold, points: 18.0) }
let string1 = NSAttributedString(
string: "Jived fox nymph grabs quick waltz. ",
attributes: [AttributedStringView.FontSetterAttributeKey : fontSetter1, /// <= Attaching the FontSetter for this string
.font: fontSetter1()
]
)
let fontSetter2: FontSetter = { UIFont.customFont(weight: .light, points: 8.0) }
let string2 = NSAttributedString(
string: "Glib jocks quiz nymph to vex dwarf. ",
attributes: [AttributedStringView.FontSetterAttributeKey : fontSetter2, /// <= Attaching the FontSetter for this string
.font: fontSetter2()
]
)
let fontSetter3: FontSetter = { UIFont.customFont(NeutrafaceSlabTextFont.self,
weight: .demi,
points: 18.0,
maximumPointSize: 24.0) }
let string3 = NSAttributedString(
string: "Sphinx of black quartz, judge my vow. ",
attributes: [AttributedStringView.FontSetterAttributeKey : fontSetter3, /// <= Attaching the FontSetter for this string
.font: fontSetter3()
]
)
let fontSetter4: FontSetter = { UIFont.customFont(weight: .heavy,
points: 48.0) }
let string4 = NSAttributedString(
string: "How vexingly quick daft zebras jump!",
attributes: [AttributedStringView.FontSetterAttributeKey : fontSetter4, /// <= Attaching the FontSetter for this string
.font: fontSetter4()
]
)
/// ...
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment