我正在尝试实现一个简单的UIButton子类,即IBDesignable。我希望能够从Interface中为控件的每个状态设置颜色。我知道这在IBInspectable关键字中是可能的。当在状态属性上使用KVO时,我遇到了IB崩溃的问题。IBDesignable调试器在deinit上崩溃。有人知道我怎么能和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)
}
}发布于 2014-10-28 12:28:42
我有类似的问题,问题是init()方法,它在重构我的代码之后导致了崩溃,它的工作原理就像一种魅力。也许它能帮到你:
#if !TARGET_INTERFACE_BUILDER
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
#endif
override func prepareForInterfaceBuilder() {
self._setup()
}发布于 2016-02-10 12:01:27
对于Xcode 7.2,@IBDesignable UIButton Subclass的通用代码如下所示:
import UIKit
@IBDesignable class MyButton: UIButton {
//this init fires usually called, when storyboards UI objects created:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupViews()
}
//This method is called during programmatic initialisation
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
//your common setup goes here
}
//required method to present changes in IB
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.setupViews()
}
}https://stackoverflow.com/questions/26608287
复制相似问题