Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a UIButton's image set programmatically?

How does one set the image of a UIButton from within the code?

I try the following but it just leaves the button as a white square.

[A1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"m1.10001.png"]] forState:UIControlStateNormal];
like image 455
some_id Avatar asked Apr 01 '26 02:04

some_id


1 Answers

Your image construction seems a bit overly complicated, but it should work. Don't forget to use the correct button type (custom):

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"m1.10001.png"] forState:UIControlStateNormal];

With newer SDKs you can omit the .png. Make sure that the image actually exists (you can store it in a temporary variable and check for nil, for example).

And of course make sure that the button exists (or is bound), i.e. non-nil, when setting the image.

like image 166
Eiko Avatar answered Apr 02 '26 21:04

Eiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!