Scholz
Scholz

Reputation: 3

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.

Upvotes: 0

Views: 119

Answers (2)

Anton Barkov
Anton Barkov

Reputation: 299

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

Upvotes: 0

Parvin Mehrabani
Parvin Mehrabani

Reputation: 1

for set image in button you should use that

yourButton.setImage(image, forState: .Normal)

Upvotes: -1

Related Questions