gpt4 book ai didi

xcode - IBDesignable UIButton子类

转载 作者:行者123 更新时间:2023-12-04 05:30:28 25 4
gpt4 key购买 nike

我正在尝试实现一个简单的UIButton子类,它是IBDesignable。我希望能够从Interface Builder为控件的每个状态设置颜色。我知道这可以通过IBInspectable关键字实现。在state属性上使用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)
}

}

最佳答案

我遇到的类似问题是init()方法,该方法在重构我的代码后导致崩溃,它像一种魅力一样工作。也许它将帮助您:

#if !TARGET_INTERFACE_BUILDER
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
#endif

override func prepareForInterfaceBuilder() {
self._setup()
}

关于xcode - IBDesignable UIButton子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26608287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com