如何在Swift扩展中添加存储属性

2016-10-12  本文已影响3649人  michael_fang

.一般而言,swift的扩展Extension只能添加计算属性,不能添加存储属性。当然,如果利用run time也可以实现extension添加存储属性的效果.
.如我给UIButton这个类添加了如下属性:

private var key: Void?
func createImageWithColor(_ color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let theImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return theImage
}
extension UIButton {
@IBInspectable var normalColor: UIColor? {
    get {
        return objc_getAssociatedObject(self, &key) as? UIColor
    }
    set(newValue) {
        objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        setBackGroundColor(normalColor ?? UIColor.white, state: UIControlState())
    }
}

@IBInspectable var highlightedColor: UIColor? {
    get {
        return objc_getAssociatedObject(self, &key) as? UIColor
    }
    set(newValue) {
        objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        setBackGroundColor(highlightedColor ?? UIColor.lightGray, state: .highlighted)
    }
}

fileprivate func setBackGroundColor(_ backGroundColor: UIColor, state: UIControlState) {
    let image = createImageWithColor(backGroundColor)
    setBackgroundImage(image, for: state)
   }
  }
上一篇 下一篇

猜你喜欢

热点阅读