Swift不允许在extension(类扩展)中直接添加属性。但是我们在实际开发中可能会遇到这种情况。
解决方案:使用objc_set/getAssociatedObject(关联属性)来实现。
场景一:给自定义button添加一个类扩展,关联name属性
class RightButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
self.name = "123"
self.setTitle(name, for: .normal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private var key: Void?
extension RightButton {
var name: String?{
get {
return objc_getAssociatedObject(self, &key) as? String
}
set {
objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
}
场景二:自定义协议btnProtocol,给协议的类扩展关联一个nick的只读属性,让自定义的button遵守该协议,获取该属性的值
protocol btnProtocol {
var age: Int {get}
}
extension btnProtocol {
var nick: String?{
get {
return "aaa"
}
}
}