UILabel 扩展,用户定义的运行时属性

UILabel extension, User defined runtime attributes

我想知道更多关于如何为 UILabel 实现文本样式的细节。 我想在故事板的 IBInspectable 字段中键入字符串,获取该值并在样式文件(切换大小写)中查找它。

我试过这样做:

  1. 设置"User defined runtime attributes".

    关键路径作为样式,

    类型为

    字符串,

    值为"hello"

    我读到我也应该在 UILabel class 中声明这个 属性 所以:

     extension UILabel{
       var style: String? {
           get(){
              return self.style // it always fails
           }
           set(newValue){
              objc_setAssociatedObject(self, "styleNew", newValue,
              objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) 
              //instead of self.style = newValue 
           }
       }
    

    }

我在 viewDidAppear 方法中将其作为 Outlet 属性:

 `print("Style", self.infoLabel.valueForKey("styleNew"))`

还有

 `print("Style", self.infoLabel.styleNew)`

当我尝试获取值时,它失败了。我收到 "bad_exc_access" 错误,我已尝试修复它,但我不明白这种行为,而且 apple.developer 上也不清楚。我只找到了教程、cornerRadius、borderColor 和类似人员的问题。 我尝试用 objc_getAssociatedObject(self, "styleNew") 替换 return return self.styleNew,但它也无济于事。

这是计算得到的 属性,您不能在 getter 中 return 本身。

如果您尝试通过设置样式字符串来设置标签的样式,我建议您保留一个样式注册表,当设置样式属性时,只需将样式应用于 UILabel。我尝试实现类似的东西并成功所以你可以看看 here.