简体   繁体   English

如何在iOS上以编程方式更改添加到NIB的UIButton的背景图像?

[英]How do I programmatically change the background image of a UIButton added to a NIB on iOS?

I've seen several questions/answers related to entirely creating a button in code, but not one which would let me know how to change the button image in code, when I originally added the button to my NIB in Interface Builder. 我最初将按钮添加到Interface Builder中的NIB时,已经看到了几个与完全在代码中完全创建按钮有关的问题/答案,但是没有一个问题/答案可以让我知道如何在代码中更改按钮图像。 I know how to change the background in Interface Builder.. but I want to change it in code, so I can change it automagically. 我知道如何在Interface Builder中更改背景。但是我想在代码中更改它,因此可以自动更改它。

Specify an IBOutlet in your controller class and connect it to the button in Interface Builder. 在控制器类中指定一个IBOutlet,并将其连接到Interface Builder中的按钮。 After the view has been loaded from the NIB file (for example in viewDidLoad), you can access the properties of the button just as if you had instantiated it in code: 从NIB文件加载视图后(例如,在viewDidLoad中),就可以访问按钮的属性,就像在代码中实例化该按钮一样:

[button setImage:myImage forState:UIControlStateNormal];

You need to create an outlet in your view controller, so add something like this: 您需要在视图控制器中创建一个插座,因此添加以下内容:

@interface mYViewController { ... IBOutlet UIButton *myButton; @interface mYViewController {... IBOutlet UIButton * myButton; ... } ...}

@property (nonatomic, retain) UIButton *myButton; @property(非原子的,保留)UIButton * myButton;

and with the relevant @synthesize etc. 以及相关的@synthesize等。

Build, then go into Interface Builder and link the button to the File's Owner (you should see myButton. Then in code you can use the setBackgroundImage method on myButton. 进行构建,然后进入Interface Builder,将按钮链接到文件的所有者(您应该看到myButton。然后在代码中,可以在myButton上使用setBackgroundImage方法。

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

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