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

标签 ios swift uilabel runtime extension-methods

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

我试过这样做:

  1. 设置“用户定义的运行时属性”。

    作为样式的关键路径,

    类型为

    字符串,

    值为“你好”

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

     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 和类似人员的问题。 我尝试将 return return self.styleNew 替换为 objc_getAssociatedObject(self, "styleNew"),但也无济于事。

最佳答案

这是一个计算属性,您不能在 getter 中返回它本身。

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

关于ios - UILabel 扩展,用户定义的运行时属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36431657/

相关文章:

ios - 在 Swift 3 中使用 AVFoundation 设置图片方向

ios - UILabel 仅在定向后才会增长

ios - 如何使用 NSString 复制中间有换行符的句子?

cocoa-touch - 从在线数据源更新 UILabel

ios - 核心数据 - 关系查询

ios - iOS 纹理加载上的 OpenGL ES - 我如何从 RGBA8888 .png 文件获取 RGB565 纹理?

ios - subview Controller 中的 topLayoutGuide

ios - SpriteKit : Getting node at CGPoint

swift - 在 Swift 3 中,如何从包含许多此类字符的字符串中替换 URL 的单个字符?

ios - 使用 UIStepper 进行 UILocalNotification 的时间