Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton setImage not working

I'm losing my mind over this one. I have UIButton connected as Outlet. I want to change it's image. In the viewDidLoad function, I try to set the image like so:

[button1 setImage:[UIImage imageNamed:@"house.png"] forState:UIControlStateNormal];

Nothing happens. However, if I use ImagePicker, it somehow works. In the ImagePickers function "didFinishPickingImage", I repeat the exactly same command as above for setting image and it works, the image is displayed normally.

I've been thinking that maybe the button's image is not refreshing itself, but trying to call [button1 setNeedsDisplay], or [button1.imageView setNeedsDisplay] or even [button1.imageView.image setNeedsDisplay] does nothing.

Does anyone have any idea about this? I've wasted two hours by now and I'm really getting frustrated, because I'm certain that the reason must be so stupid it's unbelivable.

like image 262
detra83 Avatar asked Jan 27 '12 00:01

detra83


2 Answers

Please check your button type.

If your button type is "System" you should change it to "Custom"

like image 99
Vlad Avatar answered Nov 20 '22 10:11

Vlad


Two things to do here:

#1, change your code to:

[button1 setImage:[UIImage imageNamed:@"house.png"] forState:UIControlStateNormal];

and #2

make sure your UIImage returns a valid image.

In other words,

UIImage * imageToSet = [UIImage imageNamed: @"house.png"];
if(imageToSet)
{
    [button1 setImage:[UIImage imageNamed:@"house.png"] forState:UIControlStateNormal];
} else {
    // if you see this line in your console, then you know where to look for a problem
    NSLog( @"why is my image object nil?");
}
like image 9
Michael Dautermann Avatar answered Nov 20 '22 12:11

Michael Dautermann