[Swift] 扩展存储属性

2023-01-05  本文已影响0人  巨馍蘸酱

扩展有多好用, 谁用谁知道 (一定要规范使用, 约定优于配置)

一般都是扩展方法或计算属性, 不能直接扩展存储属性

扩展存储属性

extension UIImageView {

    private struct definestruct {
        static var defineSection: Int = 0
        static var defineItem: Int = 0
    }

    var definesection: Int? {
        get {
            return objc_getAssociatedObject(self, &definestruct.defineSection) as? Int
        }
        set(value) {
            guard let num: Int = value else { return }
            objc_setAssociatedObject(self,
                                     &definestruct.defineSection,
                                     num,
                                     objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var defineitem: Int? {
        get {
            return objc_getAssociatedObject(self, &definestruct.defineItem) as? Int
        }
        set(value) {
            guard let num: Int = value else { return }
            objc_setAssociatedObject(self,
                                     &definestruct.defineItem,
                                     num,
                                     objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

使用

let imgView = UIImageView()
imgView.definesection = indexPath.section
imgView.defineitem = indexPath.item
上一篇下一篇

猜你喜欢

热点阅读