Swift实现类扩展添加属性

2022-05-20  本文已影响0人  萤火驻守心间

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"
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读