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: "Pressed-Button-Graphic@2x.png"), forState: UIControlState.Normal)
I tried this for OS X Swift:
myButtonOutlet.image(NSImage(named: "Pressed-Button-Graphic@2x.png"))
How can I change the image of my button from Swift (OS X)?
You can set the image
property on NSImage like this:
myButton.image = NSImage(named: "Pressed-Button_Graphic@2x.png")
Unlike iOS it doesn't need to use setImage()
method
The method by @brimstone did not work for me on macOS . I'm running Swift 4 .
If you have your images added to Assets.xcassets, then this should work (no file extension!):
myButton.image = NSImage(named: NSImage.Name("Pressed-Button_Graphic@2x"))
And if you just have the images imported to your main folder, then use file extension with the file name.
ps For iOS use:
button.image = UIImage(named: "Picture.png")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.