简体   繁体   English

使用Swift代码更改NSButton的图像

[英]Change image for NSButton with Swift code

I am running Xcode 7.2.1 and I am using storyboards. 我正在运行Xcode 7.2.1,我正在使用故事板。 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: 在Swift for iOS中我会这样做:

myButtonOutlet.setImage(UIImage(named: "Pressed-Button-Graphic@2x.png"), forState: UIControlState.Normal)

I tried this for OS X Swift: 我为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)? 如何从Swift(OS X)更改按钮的图像?

You can set the image property on NSImage like this: 您可以在NSImage上设置image属性,如下所示:

myButton.image = NSImage(named: "Pressed-Button_Graphic@2x.png")

Unlike iOS it doesn't need to use setImage() method 与iOS不同,它不需要使用setImage()方法

The method by @brimstone did not work for me on macOS . @brimstone的方法在macOS上对我不起作用。 I'm running Swift 4 . 我正在运行Swift 4

If you have your images added to Assets.xcassets, then this should work (no file extension!): 如果您将图像添加到Assets.xcassets,那么这应该工作(没有文件扩展名!):

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: ps适合iOS使用:

button.image = UIImage(named: "Picture.png")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM