简体   繁体   中英

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. I know how to change the background in Interface Builder.. but I want to change it in code, so I can change it automagically.

Specify an IBOutlet in your controller class and connect it to the button in 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:

[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; ... }

@property (nonatomic, retain) UIButton *myButton;

and with the relevant @synthesize etc.

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.

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.

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