6

我目前正在创建一个扩展UILabel以方便观察动态类型。收到aUIContentSizeCategoryDidChangeNotification后,我希望我的选择器使用

self.font = UIFont.preferredFontForTextStyle(someUIFontTextStyle)

wheresomeUIFontTextStyle使用与UIFontTextStyle当前展示的标签相同的标签。我曾希望这样的属性可以通过类似的东西访问self.font.fontDescriptor.textStyle,但事实似乎有点复杂。

有没有办法访问UIFontTextStyle与 a 关联的属性UILabel

解决方案

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

2 回答 2

4

正如您发现和Andy 提到的,您可以从字体描述符中获取字体的文本样式:

self.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute) as? String
于 2015-08-31T23:54:59.517 回答
3

接受的答案对于 swift 3 来说并不完全正确。 UIContentSizeCategoryDidChangeNotification的处理程序需要执行以下操作:

if let font = myUILable.font.fontDescriptor.object(forKey: UIFontDescriptorTextStyleAttribute) as? UIFontTextStyle {
    myUILabel.font = UIFont.preferredFont(forTextStyle: font)
}
于 2016-12-21T05:18:27.613 回答