Skip to content

Instantly share code, notes, and snippets.

@thillsman
Created May 15, 2020 13:39
Show Gist options
  • Save thillsman/f2903f623f0beb36a60c03e5025823ce to your computer and use it in GitHub Desktop.
Save thillsman/f2903f623f0beb36a60c03e5025823ce to your computer and use it in GitHub Desktop.
Custom dynamic type
public extension UIFont {
static func loadGothamNarrow(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {
let name: String = {
switch weight {
case .bold, .black, .heavy, .semibold:
return "GothamNarrow-Bold"
default:
return "GothamNarrow-Book"
}
}()
return UIFont(name: name, size: size) ?? systemFont(ofSize: size, weight: weight)
}
public static func font(for style: TextStyle, weight: Weight, fontFace: FontFace = .system) -> UIFont {
let desc = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
let font: UIFont = {
switch fontFace {
case .system:
return systemFont(ofSize: desc.pointSize, weight: weight)
case .gothamNarrow:
return loadGothamNarrow(ofSize: desc.pointSize, weight: weight)
}
}()
return UIFontMetrics(forTextStyle: style).scaledFont(for: font)
}
public enum FontFace {
case system
case gothamNarrow
}
// Convenience properties for standardization
public static var titleMedium: UIFont { font(for: .title2, weight: .bold, fontFace: .gothamNarrow) }
}
public extension UILabel {
public func set(font: UIFont) {
self.font = font
adjustsFontForContentSizeCategory = true
}
}
@thillsman
Copy link
Author

Call site usage is nice and clean on a label:

titleLabel.set(font: .titleMedium)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment