how can i change button background image when it is clicked in iphone?
how can i change background image of UIButton when it is clicked and it should remain as it is until another button is cl开发者_如何学编程icked.
[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.
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];
}
}
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.
you need to review UIButtonClass reference to get solutions.
Have you considered using a UISegmentedControl? This supports the function of remaining pressed until another one is pressed. Just check out the docs to find the methods for setting the image and programatically setting the selected segment.
精彩评论