Casey
Casey

Reputation: 181

How do I change an Image when a button is pressed?

Now I know this question may sound like a duplicate, but I doubt it seeing as I've researched and none of the possible duplicates answer my question. If it is a duplicate and it's been answered by all means show me the way!

But my question doesn't deal so much with a button changing an image, more so the button is the image.

So my button is an image and when pressed a sound plays and then the image changes until the sound is done. My problem is I can't get the image to change.

Now I have tried this method thinking that I could press my button and my new image would cover up my button until the sound was done:

UIImage *dolDerp = [UIImage imageNamed:@"dolphin2.png"];

[imageview setImage:dolDerp];

I have an outlet set up and it's connected to an image view object and then the action is connected to the button, so in theory when the button is pressed the new image should take over the screen. Now obviously the code needs to be tweaked so the button would go away after a few seconds when the sound is played, but my problem is I can't even get the button to display. I also would prefer to just have the button objects image change if possible? If anyone could offer some help it's much appreciated!

Upvotes: 1

Views: 570

Answers (2)

atomkirk
atomkirk

Reputation: 3801

What @Mahmoud Fayez suggested is good. In code, the proper way to set a buttons image/background image is [button setImage:image forState:UIControlStateNormal] or the similar method for setBackgroundImage

If you are using IB though, it is indeed best to set the different images for different states in IB, then change the buttons state (which will then change the buttons image) in code.

Upvotes: 1

Mahmoud Fayez
Mahmoud Fayez

Reputation: 3459

the best thing is in Interface Builder assign the two images to the button Normal/Selected states.

in code just use this line:

myButton.selected = YES;
//or 
myButton.selected = NO;

Upvotes: 2

Related Questions