在 UIButton 上覆盖 'isSelected' 或 'isEnabled' 不起作用

Overriding 'isSelected' or 'isEnabled' on UIButton does not work

我正在尝试创建一个自定义 UIButton 子类,它在 normalselecteddisabled 状态下具有不同的颜色。我的按钮位于一个框架中,然后导入到一个应用程序中,但是我在这里放置的每个代码片段,我都在主应用程序和框架中尝试过——我知道它不应该有任何区别,但我想涵盖我的基地。我无法让它工作以挽救我的生命。

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")
    }
}

我已经无计可施了。我对此有什么误解?

我认为意义相同。您可以采取以下一些步骤来重现其工作方式。您可能错过了这些步骤中的任何一个。

  1. 创建 BrokenButton class,它是 UIButton 的子class。正如您在上述问题中所做的那样。

  2. 打开故事板或 xib 并将 UIButton 拖到故事板或 xib 中

  3. Select 您刚刚拖入 storyboard/xib 的 UIButton,并在识别检查器中,确保将 class BrokenButton

  4. 在您的 ViewController 中创建一个 Outlet,如下所示: @IBOutlet weak var button: BrokenButton?

  5. 在您的 storyboard/xib 连接检查器中,将按钮连接到您的 IBOutlet

  6. 然后在您的 viewcontroller 中将按钮设置为启用或禁用,如下所示: button?.isEnabled = true

  7. 正在制作中。

@Daniel 由于 BrokenButton class 在框架内部,您需要使用 open 关键字从其他模块外部进行访问。所以只需在 BrokenButton class 和 isEnabled 属性.

之前添加 open 关键字
open class BrokenButton: UIButton {
    override open var isEnabled: Bool {
        didSet {
            print("This is never called no matter what I do")
        }
    }
}

An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

有关 open 关键字的更多信息..阅读 Whosebug 答案