开发者

iOS: change png in a bar button item

I put in a tolbar a bar button item, and I set it with a png (first.png) and when I push it I want to change its png in "second.png"

This code doesn't work fine:

UIImage *first = [UIImage imageNamed:@"first.png"];
UIImage *second = [UIImage imageNamed:@"second.png"];

if ([sender isSelected]) 
{  
    [sender setImage:first forState:UIControlStateNormal];  
    [sender setSelected:NO];  

}
else 
{     
    [sender set开发者_StackOverflowImage:second forState:UIControlStateSelected]; 
    [sender setSelected:YES];

}


The current answerers do not realize that UIBarButtonItem does NOT inherit from UIButton, so setImage:forState: will most definitely not work. UIBarButtonItems cannot be set for different states. You can, however, utilize something like this (declared in the UIBarItem docs):

sender.image = [UIImage imageNamed:@"first.png"];


I'm not clear on why you have an if block in there. Can't you initialize both state images as a one-off initialization step? I.e.

[sender setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal];  
[sender setImage:[UIImage imageNamed:@"second.png"] forState:UIControlStateSelected]; 

In fact, this can probably be done in Interface Builder if you don't need to do it programmatically.


Just write after creation of button this lines:

UIImage *first = [UIImage imageNamed:@"first.png"];
UIImage *second = [UIImage imageNamed:@"second.png"];

[sender setImage:first forState:UIControlStateNormal];
[sender setImage:second forState:UIControlStateSelected]; 

You don't need if-else statement.

Updated:

CGRect myFrame;
UIButton *myButton = [[UIButton alloc] initWithFrame:myFrame];
[myButton setImage:[UIImage imageNamed:@"first.png"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"second.png"] forState:UIControlStateSelected];
UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:myButton];
[myButton release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜