我正在尝试实现一个简单的UIButton子类,它是IBDesignable的。我想要能够从Interface Builder为控件的每个状态设置颜色。我知道使用IBInspectable关键字可以实现这一点。但是当我在state属性上使用KVO时,我的IB会崩溃。在deinit时,IBDesignable调试器会崩溃。有人知道我如何同时使用KVO和IBDesignable吗?
@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)
}
}
init(frame:)
中删除setupViews()
的调用,IB和应用程序仍然可以正常工作。我们需要从那个init调用设置的原因是什么? - Paul Van WierensetupViews()
中设置断点并检查是谁在调用它 :) - skywinder