我们在分类中添加存储属性时,往往会有一个 Extensions must not contain stored properties 的错误提醒,如下图:
解决这个问题就是给分类添加关联属性,主要用到的方法是:
public func objc_setAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: Any?, _ policy: objc_AssociationPolicy)
public func objc_getAssociatedObject(_ object: Any, _ key: UnsafeRawPointer) -> Any?
为分类添加一个 UILabel 属性:
struct associatedKey {
static var key = "xz_badge"
}
private var xz_labelBadge: UILabel? {
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &(associatedKey.key), newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
get {
return objc_getAssociatedObject(self, &(associatedKey.key)) as? UILabel
}
}
调用
xz_labelBadge = UILabel()
// 创建
xz_labelBadge?.layer.cornerRadius = 10
xz_labelBadge?.layer.masksToBounds = true
xz_labelBadge?.backgroundColor = .red
xz_labelBadge?.font = UIFont.systemFont(ofSize: 10)
xz_labelBadge?.textAlignment = .center
xz_labelBadge?.frame = CGRect(x: CGFloat(x), y: CGFloat(y), width: 20, height: 20)
// 添加红点
self.addSubview(xz_labelBadge!)