I wan开发者_运维问答t to change the button image on buttons click event. Here is what i am trying.
-(IBAction)editObjectImage:(id)sender
{
if (editButtonState == NO)
{
[editButton setImage:nil forState:UIControlStateNormal];
[editButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
}
else
{
[editButton setImage:nil forState:UIControlStateNormal];
[editButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
}
}
But my Button image is not changing. What's wrong with code?
I think you aren't getting round to changing editButtonState
. Your code can be reduced to.
-(IBAction)editObjectImage:(id)sender
{
UIButton *theButton = (UIButton*)sender;
if (editButtonState == NO) {
[theButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
} else {
[theButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
}
editButtonState = !editButtonState;
}
This is my working code:
NSString *shoppingListButtonImageName = @"notepad-selected";
UIImage *slImage = [UIImage imageNamed:shoppingListButtonImageName];
//put a breakpoint here to check that slImage is not nil.
[self.shoppingListButton setImage:slImage forState:UIControlStateNormal];
On button click you have to set image like this;
[editButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateHighlighted];
Check if the images are added properly (your [UIImage imageNamed:@""]) is not returning nil ? , otherwise it should work properly.
精彩评论