Search code examples
swiftmacoscocoansbutton

Change image for NSButton with Swift code


I am running Xcode 7.2.1 and I am using storyboards. I added an "Image Button" to my storyboard and set the image in the attributes inspector. I then created an outlet and action for the button in my code.

When I press the button I want its image to change. In Swift for iOS I would do this:

myButtonOutlet.setImage(UIImage(named: "[email protected]"), forState: UIControlState.Normal)

I tried this for OS X Swift:

myButtonOutlet.image(NSImage(named: "[email protected]"))

How can I change the image of my button from Swift (OS X)?


Solution

  • You can set the image property on NSImage like this:

    myButton.image = NSImage(named: "[email protected]")
    

    Unlike iOS it doesn't need to use setImage() method