Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get weight of a UILabel?

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?

like image 251
Lalit Kumar Avatar asked Feb 08 '18 13:02

Lalit Kumar


1 Answers

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)

like image 142
DeFrenZ Avatar answered Sep 28 '22 02:09

DeFrenZ