简体   繁体   English

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

[英]UILabel extension, User defined runtime attributes

I would like to know more details how to implement text styles to UILabel. 我想知道如何为UILabel实现文本样式的更多细节。 I want to type String in IBInspectable field in Storyboard, get this value and look for this it in style file (switch case). 我想在Storyboard的IBInspectable字段中键入String,获取此值并在样式文件(switch case)中查找它。

I've tried to do this this way: 我试过这样做:

  1. Set "User defined runtime attributes". 设置“用户定义的运行时属性”。

    Key Path as style, 作为风格的关键路径,

    Type as 输入为

    String, 串,

    value as "hello" 价值为“你好”

    I' ve read that I should declare also this property in UILabel class so: 我已经读过我应该在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 } } 

    } }

I'm calling it in viewDidAppear method as an Outlet property: 我在viewDidAppear方法中将其作为Outlet属性调用:

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

and also 并且

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

When I try to get value it fails. 当我试图获得价值时,它失败了。 I'm getting "bad_exc_access" error, I've tried to repair it but I don't understand this behavior and on apple.developer is nothing clear. 我收到“bad_exc_access”错误,我试图修复它,但我不明白这种行为,并且在apple.developer上并不清楚。 I found only tutorials, issues with cornerRadius, borderColor and staff like that. 我发现只有教程,有关cornerRadius,borderColor和类似工作人员的问题。 I've tried to replace return return self.styleNew with objc_getAssociatedObject(self, "styleNew") , but it doesn't help too. 我试图用objc_getAssociatedObject(self, "styleNew")替换return return self.styleNew ,但它也没有帮助。

This is a computed property and you cannot return itself in the getter. 这是一个计算属性,你不能在getter中返回它自己。

If you are trying to style the label by setting the style string, I suggest you keep a registry of styles and when the style attribute gets set, just apply the style to the UILabel. 如果您尝试通过设置样式字符串来设置标签的样式,我建议您保留样式的注册表,并且在设置样式属性时,只需将样式应用于UILabel。 I tried to implement something similar with success so you can take a look here . 我试图实现类似的成功,所以你可以看看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM