Ios 如何查找UILabel的现有UIFontTextStyle?
我目前正在Ios 如何查找UILabel的现有UIFontTextStyle?,ios,iphone,swift,uilabel,uifontdescriptor,Ios,Iphone,Swift,Uilabel,Uifontdescriptor,我目前正在UILabel上创建一个扩展,以便于观察动态类型。一旦收到UIContentSizeCategoryDidChangeNotification,我希望我的选择器使用 self.font = UIFont.preferredFontForTextStyle(someUIFontTextStyle) 其中someUIFontTextStyle使用与当前显示的标签相同的UIFontTextStyle。我曾希望这样一个属性可以通过像self.font.fontDescriptor.textS
UILabel
上创建一个扩展,以便于观察动态类型。一旦收到UIContentSizeCategoryDidChangeNotification
,我希望我的选择器使用
self.font = UIFont.preferredFontForTextStyle(someUIFontTextStyle)
其中someUIFontTextStyle
使用与当前显示的标签相同的UIFontTextStyle
。我曾希望这样一个属性可以通过像self.font.fontDescriptor.textStyle这样的东西访问,但事实似乎有点复杂
是否有方法访问与UILabel
关联的UIFontTextStyle
属性
解决方案
正如您所发现的,您可以从字体描述符获取字体的文本样式:
self.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute) as? String
对于swift 3,公认的答案并不完全正确。UIContentSizeCategoryDidChangeNotification的处理程序需要执行以下操作:
if let font = myUILable.font.fontDescriptor.object(forKey: UIFontDescriptorTextStyleAttribute) as? UIFontTextStyle {
myUILabel.font = UIFont.preferredFont(forTextStyle: font)
}
非常感谢!你的解决方案正是我所需要的。或者,我发现访问myLabel.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute)作为?字符串将在不使用非公钥的情况下获得相同的成功。
UIFontDescriptorTextStyleAttribute
是正确的键。@Andy谢谢。我已经更新了答案,相信你。
if let font = myUILable.font.fontDescriptor.object(forKey: UIFontDescriptorTextStyleAttribute) as? UIFontTextStyle {
myUILabel.font = UIFont.preferredFont(forTextStyle: font)
}