how can i change button background image when it is clicked in iphone?
15,085
Solution 1
[myButton setImage:[UIImage imageNamed:@"btn_normal.png"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"btn_highlighted.png"] forState:UIControlStateHighlighted];
[myButton setImage:[UIImage imageNamed:@"btn_highlighted.png"] forState:UIControlStateSelected];
myButton.showsTouchWhenHighlighted = YES;
Fourth line myButton.showsTouchWhenHighlighted = YES; will do the trick. Please try.
Solution 2
Working Code :
// 1) Give tag to all needed button
// 2) check which button is selected by "sender tag"
// 3) set all other buttons to not selected
-(IBAction) buttonPressed:(id)sender
{
if ([sender isSelected])
{
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:NO];
}
else
{
[sender setImage:selectedImage forState:UIControlStateSelected];
[sender setSelected:YES];
}
}
Solution 3
you need to review UIButtonClass reference to get solutions.
Solution 4
You will need to set the image every time user taps any button on your view. So when user taps your button, set its image to something that you want(lets assume thats its darker) and the rest of the buttons to normal image(lets assume lighter). Then when user taps other button, repeat the process.
[yourButton setImage:[UIImage imageNamed:youImage] forState:UIControlStateNormal];
Hope this helps.
Comments
-
Devang almost 2 years
how can i change background image of UIButton when it is clicked and it should remain as it is until another button is clicked.
-
Devang about 13 yearsit changes the image when it pressed but after then it comes back to its orginal(old) image...... i want to keep the new image and dont want to allow user to touch that button again (disable) with new image
-
Vaibhav Tekam about 13 yearscan you try to use yourButton.enabled property to use.
-
Devang about 13 yearsi have tried that but its changes the background image color as setting enable or disable has its own colors
-
Totumus Maximus about 11 years+1: myButton.showsTouchWhenHighlighted, I learned something new today!:O thanks, didn't know this was there until now ^^