我想實現一個簡單的IBDesignable UIButton子類。我希望能夠爲Interface Builder的每個控件狀態設置顏色。我知道這可能與IBInspectable關鍵字。在狀態屬性上使用KVO時,我遇到IB崩潰問題。 IBDesignable調試器在deinit時崩潰。有誰知道我可以如何與KVO和IBDesignable一起工作?IBDesignable UIButton子類
@IBDesignable
class UIButtonActionButton: UIButton {
@IBInspectable var defaultColour: UIColor = UIColor.blueColor() {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var selectedColour: UIColor = UIColor.blueColor()
@IBInspectable var disabledColour: UIColor = UIColor.grayColor()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
self._setup()
}
private func _setup(){
self.addObserver(self, forKeyPath: "state", options: NSKeyValueObservingOptions.New, context: nil)
self.layer.cornerRadius = 5.0
self.layer.masksToBounds = true
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
if self.highlighted {
CGContextSetFillColorWithColor(context, selectedColour.CGColor)
CGContextFillRect(context, self.bounds)
} else if self.state == UIControlState.Disabled {
CGContextSetFillColorWithColor(context, disabledColour.CGColor)
CGContextFillRect(context, self.bounds)
} else {
CGContextSetFillColorWithColor(context, defaultColour.CGColor)
CGContextFillRect(context, self.bounds)
}
}
deinit {
self.removeObserver(self, forKeyPath: "state", context: nil)
}
}
感謝尖丹尼爾。我嘗試了上述,現在抱怨說我的IBInspectable屬性不符合鍵值編碼。所以我只是在運行時使用宏來添加/刪除觀察者。接受MACRO提示的這個答案。 – 2014-10-28 14:49:42