【问题标题】:How do I find the existing UIFontTextStyle of a UILabel?如何找到 UILabel 的现有 UIFontTextStyle?
【发布时间】:2015-08-31 22:08:49
【问题描述】:

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

设置标签的字体
self.font = UIFont.preferredFontForTextStyle(someUIFontTextStyle)

其中someUIFontTextStyle 使用与当前标签相同的UIFontTextStyle。我曾希望可以通过self.font.fontDescriptor.textStyle 之类的方式访问这样的属性,但事实似乎有点复杂。

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

解决方案

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

【问题讨论】:

    标签: ios iphone swift uilabel uifontdescriptor


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!您的解决方案正是我所需要的。或者,我发现访问myLabel.font.fontDescriptor().objectForKey(UIFontDescriptorTextStyleAttribute) as? String 将产生同样的成功,而无需使用非公钥。
    • UIFontDescriptorTextStyleAttribute 是正确的密钥。
    • @Andy 谢谢。我已经更新了答案并记入了你的功劳。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多