I am using Interface Builder, in which I added a UIButton
to the view.
I defined the button selected by default and selected my image for the selected state (Use drop-down list in Inspector window to choose "Selected State Configuration" before selecting the image).
Create an IBAction
in the controller and connect the button to that action.
Then see the code below:
-(IBAction) toggleUIButtonImage:(id)sender{
if ([sender isSelected]) {
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:NO];
} else {
[sender setImage:selectedImage forState:UIControlStateSelected];
[sender setSelected:YES];
}
}
I think this is quite a smooth solution. Hope it helps!
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.
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];
To change the image for the selected state you have to call setImage
for state UIControlStateSelected
. You can set separate images for different states (Normal, Highlighted, Disabled, Selected, etc).
If you want to change the image when the button is clicked, this way, works perfectly:
-(IBAction)buttonClicked: (id)sender
{
UIButton *buttonObj = (UIButton*)sender;
[buttonObj setBackgroundImage:[UIImage imageNamed:@"myImage.png"]
forState:UIControlStateNormal];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With