Alex Rivera | Logout

Changing image on UIButton when user presses that button on an iPhone

Asked 2009-07-02T05:48:18.363
37

I want to change the image on UIButton when the User presses that button. I wrote:

btnthumbnail2 setImage:[UIImage imageNamed:@"leaderboard_ov.png"] forState:UIControlStateNormal];

and after that I changed the view.

The image is changing, but it does not display the changed image. I think the control goes to the next view, and that's why it is happening. How can I show the change?

Edit
Report

3 Answers

23

This is the simplest way that I am doing it and it works every time

-(void)buttonTouched:(id)sender
{
 UIButton *btn = (UIButton *)sender;

 if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"icon-Locked.png"]])
    {
       [btn setImage:[UIImage imageNamed:@"icon-Unlocked.png"] forState:UIControlStateNormal];
       // other statements
    }
 else
   {
       [btn setImage:[UIImage imageNamed:@"icon-Locked.png"] forState:UIControlStateNormal];
       // other statements
   }
}

You can use other similar checks for other states such as SELECTED, ENABLED, HIGHLIGHTED.

answered 2012-12-01T09:12:04.063
11

The code you have there should work fine, but I'm guessing that the button image doesn't appear changed until the next run through the event loop, so you don't see it before the view gets switched out.

It's kind of a hack, but you could try delaying the view change just slightly so that the button will update.

So instead of this:

[btnthumbnail2 setImage:[UIImage imageNamed:@"leaderboard_ov.png"] forState:UIControlStateNormal];
[self showMyOtherView];

Try this:

[btnthumbnail2 setImage:[UIImage imageNamed:@"leaderboard_ov.png"] forState:UIControlStateNormal];
[self performSelector:@selector(showMyOtherView) withObject:self afterDelay:0.01];
answered 2009-07-02T07:39:15.573
2

Building on Nicsoft's answer.

-(void)viewDidLoad {
    [super viewDidLoad];
    [self.button setImage:[UIImage imageNamed:@"unselectedImageName"] forState:UIControlStateNormal];
    [self.button setImage:[UIImage imageNamed:@"selectedImageName"] forState:UIControlStateSelected];
}

-(IBAction)toggleButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    // Add logic here
}
answered 2012-06-17T22:06:37.777

Your Answer