6

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
lauragone
  • 63
  • 6

2 Answers2

4

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
Community
  • 1
  • 1
  • Thanks so much! Your solution does precisely what I needed. Alternatively, I found accessing `myLabel.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute) as? String` will yield the same success without using a non-public key. – lauragone Sep 02 '15 at 15:56
  • `UIFontDescriptorTextStyleAttribute` is the correct key. – pronebird Oct 17 '15 at 18:52
  • @Andy Thanks. I've updated the answer and credited you. –  Oct 17 '15 at 19:48
3

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)
}
pbm
  • 5,081
  • 4
  • 18
  • 31