swiftappkitnsbuttondidset

didSet not updating NSImage


I am trying to update the Image of an NSButton(Image) through a toggle in my storyboard. The NSButton Image is not changing though.

Here my ViewController IBAction Code:

    @IBAction func ButtonState(_ sender: NSSwitch) {
    let stateOfButton = sender.state
    if (stateOfButton.rawValue == 1){
        testButton.isEnabled = true

    
    }
    else{
        testButton.isEnabled = false

    }
}

Here a snippet from my NSButton Class with the modifications:

override var isEnabled: Bool{
    didSet{
        if(self.isEnabled){
            self.image = NSImage(named: "TestEnabled")
            print("TestEnable")
        }
        else{
            self.image = NSImage(named: "TestDisabled")
            self.state = NSControl.StateValue(rawValue: 0)
            print("NoEnable")
        }
        
    }

The print statements are executed on toggling the switch but the image is not changing.


Solution

  • Please double check that both of the named images exist. Below is a prettified version of your code and it works as expected:

    class ViewController: NSViewController {
        @IBOutlet weak var button: MyButton!
        
        @IBAction func switchClicked(_ sender: NSSwitch) {
            button.isEnabled = sender.state == .on
        }
    }
    
    class MyButton: NSButton {
        override var isEnabled: Bool {
            didSet {
                image = isEnabled
                    ? NSImage(named: NSImage.statusAvailableName)
                    : NSImage(named: NSImage.statusUnavailableName)
            }
        }
    }
    

    Button switch demo