我正在尝试制作一个自定义的UIButton子类,它在normal
,selected
和disabled
状态中具有不同的颜色。我的按钮位于一个框架中,然后导入到一个应用程序中,但我放在这里的每个代码片段,我都在主应用程序和框架中尝试过 - 我知道它应该没有任何区别,但我想覆盖我的基地。我无法让它来拯救我的生命。
class BrokenButton: UIButton {
override var isEnabled: Bool {
didSet {
print("This is never called no matter what I do")
}
}
}
我已经尝试使用KVO来观察isEnabled
的价值,因为重写setter不起作用:
class BrokenButton2: UIButton {
required init() {
super.init(frame: .zero)
addObserver(self, forKeyPath: #keyPath(isEnabled), options: [.new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
print("Never called")
}
}
我在这里结束了我的智慧。我对此有何不妥?
@Daniel由于BrokenButton类在Framework内部,因此您需要使用open关键字从其他模块外部进行访问。因此,只需在BrokenButton类和isEnabled属性之前添加open关键字。
open class BrokenButton: UIButton {
override open var isEnabled: Bool {
didSet {
print("This is never called no matter what I do")
}
}
}
开放类可以在定义模块之外访问和子类化。开放类成员可在定义模块外部访问和覆盖。
有关open
keyword..read this stackoverflow答案的更多信息
我认为与意义有关。您可以采取以下步骤来重现其工作方式。您可能错过了这些步骤中的任何一个。
BrokenButton
@IBOutlet weak var button: BrokenButton?
button?.isEnabled = true