xcode iOS:更改条形按钮项中的 png
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7284306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS: change png in a bar button item
提问by cyclingIsBetter
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"
我在工具栏中放置了一个条形按钮项,并使用 png (first.png) 设置它,当我按下它时,我想在“second.png”中更改它的 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 setImage:second forState:UIControlStateSelected];
[sender setSelected:YES];
}
回答by esqew
The current answerers do not realize that UIBarButtonItem
does NOT inherit from UIButton, so setImage:forState:
will most definitely notwork. UIBarButtonItems cannotbe set for different states. You can, however, utilize something like this (declared in the UIBarItem docs):
当前的回答者没有意识到这UIBarButtonItem
不是从 UIButton 继承的,因此setImage:forState:
绝对不会起作用。不能为不同的状态设置UIBarButtonItems 。但是,您可以使用这样的东西(在UIBarItem 文档中声明):
sender.image = [UIImage imageNamed:@"first.png"];
回答by Nekto
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.
您不需要 if-else 语句。
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];
回答by Clafou
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.
我不清楚为什么你在那里有一个 if 块。您不能将两个状态图像初始化为一次性初始化步骤吗?IE
[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.
事实上,如果您不需要以编程方式进行,这可能可以在 Interface Builder 中完成。