Iphone – UIButton with image losing its newly set image

iphoneuibuttonuiimageuiimageview

I've got a UIButton (custom, with image) set up in IB which is an IBOutlet in my code.

In my viewDidLoad method in the viewController, I am trying to change the existing image of the UIButton

UIImage *newbuttonimage = [UIImage imageNamed:@"newbuttonimage.png"];
testbutton.imageView.image = newbuttonimage;

OK, that works when starting the app, but whenever you interact with the button (press it), it changes to the original image (set in IB). There's no other code to change images in the whole project, so what is going on?

Incidentally, when I put the above code in any other part of my project it doesn't change the image.

Best Answer

You should try using setImage:forState instead of assigning the image directly; there are multiple states of a UIButton and, if not set properly, may yield unwanted behaviors (akin to the ones you're seeing).

Related Topic