Skip to content

Instantly share code, notes, and snippets.

@keehun
Last active February 15, 2019 17:48
Show Gist options
  • Select an option

  • Save keehun/719c9dc9abbdf56b99c6fb7d63adce6f to your computer and use it in GitHub Desktop.

Select an option

Save keehun/719c9dc9abbdf56b99c6fb7d63adce6f to your computer and use it in GitHub Desktop.
Practical Dynamic Type, Part 3: Attributed Strings
import Foundation
import UIKit
// MARK: - AttributedStringView
class AttributedStringView: UIView {
/// `FontSetter` is a closure type used to recalculate the font size.
typealias FontSetter = () -> UIFont
/// 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: [.font: fontSetter1()]
)
let fontSetter2: FontSetter = { UIFont.customFont(weight: .light, points: 8.0) }
let string2 = NSAttributedString(
string: "Glib jocks quiz nymph to vex dwarf. ",
attributes: [.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: [.font: fontSetter3()]
)
let fontSetter4: FontSetter = { UIFont.customFont(weight: .heavy,
points: 48.0) }
let string4 = NSAttributedString(
string: "How vexingly quick daft zebras jump!",
attributes: [.font: fontSetter4()]
)
var totalAttributedString = NSMutableAttributedString(attributedString: string1)
totalAttributedString.append(string2)
totalAttributedString.append(string3)
totalAttributedString.append(string4)
let label = UILabel(numberOfLines: 0)
label.attributedText = totalAttributedString
label.adjustsFontForContentSizeCategory = true
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(display)
NSLayoutConstraint.activate([
display.topAnchor.constraint(equalTo: topAnchor),
display.bottomAnchor.constraint(equalTo: bottomAnchor),
display.leadingAnchor.constraint(equalTo: leadingAnchor),
display.trailingAnchor.constraint(equalTo: trailingAnchor),
])
}
/// Although "required," we don't have to implement init(coder:) for now
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented for this article.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment