How do I find the existing UIFontTextStyle of a UILabel?

2k Views Asked by At

I'm currently creating an extension on UILabel to facilitate observing dynamic type. Once a UIContentSizeCategoryDidChangeNotification is received, I'd like my selector to set the label's font by using

self.font = UIFont.preferredFontForTextStyle(someUIFontTextStyle)

where someUIFontTextStyle uses the same UIFontTextStyle the label currently exhibits. I had hoped such a property would be accessible via something like self.font.fontDescriptor.textStyle, but the truth seems a bit more convoluted.

Is there a way to access the UIFontTextStyle property associated with a UILabel?

Solution

self.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute) as? String
2

There are 2 best solutions below

0
On BEST ANSWER

The accepted answer is not quite right for swift 3. The handler for UIContentSizeCategoryDidChangeNotification needs to do the following:

if let font = myUILable.font.fontDescriptor.object(forKey: UIFontDescriptorTextStyleAttribute) as? UIFontTextStyle {
    myUILabel.font = UIFont.preferredFont(forTextStyle: font)
}
3
On

As you discovered and Andy mentioned, you can get the font's text style from its font descriptor:

self.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute) as? String