Skip to content

Instantly share code, notes, and snippets.

@hiddevdploeg
Last active August 23, 2022 12:14
Show Gist options
  • Save hiddevdploeg/bcb5112dc57c15eb404a3a7e167b0304 to your computer and use it in GitHub Desktop.
Save hiddevdploeg/bcb5112dc57c15eb404a3a7e167b0304 to your computer and use it in GitHub Desktop.
Expanded and Condensed Font for SwiftUI
public extension Font {
init(uiFont: UIFont) {
self = Font(uiFont as CTFont)
}
static func expanded(_ style: UIFont.TextStyle, size: CGFloat? = nil, weight: Font.Weight = .regular) -> Font {
var descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
let traits: [UIFontDescriptor.TraitKey:Any] = [.width: 1.5]
descriptor = descriptor.addingAttributes([.traits: traits])
let uiFont = UIFont(descriptor: descriptor, size: size ?? descriptor.pointSize)
return Font(uiFont: uiFont).weight(weight)
}
static func condensed(_ style: UIFont.TextStyle, size: CGFloat? = nil, weight: Font.Weight = .regular) -> Font {
var descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)
let traits: [UIFontDescriptor.TraitKey:Any] = [.width: -0.2]
descriptor = descriptor.addingAttributes([.traits: traits])
let uiFont = UIFont(descriptor: descriptor, size: size ?? descriptor.pointSize)
return Font(uiFont: uiFont).weight(weight)
}
}
// Example usage: Font.expanded(.largeTitle, weight: .heavy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment