4

I am trying to make a UIButton extension that prints something when setting the isEnabled value. But it doesn't seem to be triggered. (Doesn't print):

extension UIButton {
    override open var isEnabled: Bool {
        willSet {
            print("About to set isEnabled to \(newValue)")
            // print isn't triggered when I set isEnabled later
        }
    }
}

But it works when I use the extension on a custom subclass of UIButton:

class CustomUIButton: UIButton {}

extension CustomUIButton {
    override open var isEnabled: Bool {
        willSet {
            print("About to set isEnabled to \(newValue)")
            // print is triggered when I set isEnabled later
        }
    }
}

The UIButtons are added in the storyboard when it doesn't work but if they are added in code then it works as expected. Why is this? And how can I make it work on UIButtons added in storyboard?

Hadus
  • 1,551
  • 11
  • 22
  • saw how to do this on: https://stackoverflow.com/questions/5715092/disabled-uibutton-not-faded-or-grey – Hadus Jun 16 '20 at 19:27
  • I just added your extension... added a `UIButton`... in `viewDidLoad()` called `myButton.isEnabled = false` ... and I see *About to set isEnabled to false* in the debug console. – DonMag Jun 16 '20 at 20:37
  • Hmm probably it is because I use the storyboard... I edited the question. – Hadus Jun 17 '20 at 15:14
  • For now I am just using the subclass implementation and setting the UIButton's class in storyboard. – Hadus Jun 17 '20 at 15:16
  • Curious... works fine in `iOS 12` -- doesn't work in `iOS 13`. Note: same behavior with trying to override `isHighlighted` – DonMag Jun 17 '20 at 15:42
  • 5
    You cant override methods or properties, this guy explains why: https://stackoverflow.com/questions/38213286/overriding-methods-in-swift-extensions#:~:text=It%20is%20not%20possible%20to,they%20cannot%20override%20existing%20functionality.&text=The%20compiler%20is%20allowing%20you,for%20compatibility%20with%20Objective%2DC. – ERP Jun 17 '20 at 17:05
  • @PRE Why would it work when making a subclass and also in `IOS 12` then? This counts as adding new functionality. – Hadus Jun 17 '20 at 20:34
  • it also depends on how the button is initialised, if the property is set in init methods, the willSet/didSet method will be not called – nghiahoang Jun 30 '20 at 03:09

0 Answers0