User from storyboard or programatically can set font weight as regular, semi bold etc.
I want to read weight for any font label.
I tried po label.font.description and font-weight is there and but there is no exposed variable to get weight from font.
Is it possible?
It seems that fontDescriptor.fontAttributes won't return all the attributes of a font. Luckily fontDescriptor.object(forKey: .traits) will, so we can hop onto that.
extension UIFont {
    var weight: UIFont.Weight {
        guard let weightNumber = traits[.weight] as? NSNumber else { return .regular }
        let weightRawValue = CGFloat(weightNumber.doubleValue)
        let weight = UIFont.Weight(rawValue: weightRawValue)
        return weight
    }
    private var traits: [UIFontDescriptor.TraitKey: Any] {
        return fontDescriptor.object(forKey: .traits) as? [UIFontDescriptor.TraitKey: Any]
            ?? [:]
    }
}
and then it's as simple as label.font.weight
(This is fundamentally equivalent to https://stackoverflow.com/a/48688000/1288097 but it uses UIKit APIs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With