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

问题描述 投票:0回答:2

我正在尝试制作一个自定义的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")
    }
}

我在这里结束了我的智慧。我对此有何不妥?

ios swift uibutton key-value-observing
2个回答
1
投票

@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答案的更多信息


0
投票

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

  1. 创建BrokenButton类,它是UIButton的子类。正如你在上面的问题中所做的那样。
  2. 打开storyboard或xib并将UIButton拖到故事板或xib中
  3. 选择您刚刚拖入storyboard / xib的UIButton,并在标识检查器中,确保您创建类BrokenButton
  4. 在ViewController中创建一个这样的插座:@IBOutlet weak var button: BrokenButton?
  5. 在storyboard / xib,连接检查器中,将按钮连接到IBOutlet
  6. 然后在viewcontroller中,将按钮设置为启用或禁用,如下所示:button?.isEnabled = true
  7. 这是在works.enter image description here
© www.soinside.com 2019 - 2024. All rights reserved.