Set Specific Font Weight for UILabel in Swift
You can use this extension. It assigns the weight to the fontDescriptor's weight key and instantiate your font with this new descriptor.
extension UIFont {
func withWeight(_ weight: UIFont.Weight) -> UIFont {
let newDescriptor = fontDescriptor.addingAttributes([.traits: [
UIFontDescriptor.TraitKey.weight: weight]
])
return UIFont(descriptor: newDescriptor, size: pointSize)
}
}
I couldn't get the UIFontDescriptor
to work with the font weight trait but there is another approach.
let font = UIFont.systemFont(ofSize: 20, weight: .light)
Replace .light
with whichever value you want from UIFont.Weight
which basically matches the dropdown list shown in your question.
The very old thread, but someone may be interested in how to do it in Swift.
UIFont.Weight
defines all of the options:
- ultraLight
- thin
- light
- regular
- medium
- semibold
- bold
- heavy
- black
you can use simply like that, e.g.:
label.font = UIFont.systemFont(ofSize: size, weight: .bold)
or if you want to keep the previous size:
label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)