ios 在 Iphone 中选择按钮时更改按钮的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7335289/
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
Changing Image of Button When the button is selected In Iphone
提问by Ranjit
I have two buttons on my first view,so when I click on one of the button the view changes,so I have two images one for the default state and one for the selected state, first i tried with xib,goin into the properties and changing the states and then selecting the proper images and when I build and run my code,On cliking the image doesnt change..
我的第一个视图上有两个按钮,因此当我单击其中一个按钮时,视图会发生变化,因此我有两个图像,一个用于默认状态,一个用于选定状态,首先我尝试使用 xib,进入属性并更改状态,然后选择正确的图像,当我构建和运行我的代码时,点击图像不会改变..
So I did this way through code
所以我通过代码这样做
- (IBAction) handleButton:(id)sender
{
UIButton *button = (UIButton*)sender;
int tag = [button tag];
switch (tag)
{
case BUTTON_1:
if ([m_Button1 isSelected])
{
[m_Button2 setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[m_Button1 setSelected:NO];
}
else
{
[m_Button1 setImage:[UIImage imageNamed:@"image_pressed.png"] forState:UIControlStateSelected];
[m_Button1 setSelected:YES];
}
[self displaymethod1];
break;
case BUTTON_2:
[self displaymethod2];
break;
default:
break;
}
}
here the image changes when i click on it and i go to diffrent view..when i again come back to my first view,the button is still in selected mode..so How shall i fix this..
在这里,当我点击它时图像会发生变化,然后我转到不同的视图..当我再次回到我的第一个视图时,该按钮仍处于选定模式..那么我该如何解决这个问题..
Waiting for your reply
等待你的回复
回答by rjgonzo
I think is a bit simpler through IB.
我认为通过IB更简单一些。
When you add a regular Round Rect Button
in IB you can modify its behavior by going to the Button
section in the Attributes Inspector
panel.
当您Round Rect Button
在 IB 中添加常规时,您可以通过转到面板中的Button
部分来修改其行为Attributes Inspector
。
First select the images you want for it's default state by leaving the State Config
in Default
. There is an image
and a background image
properties for this. Once that is set, you can change the State Config
to Highlighted
and select the image you want to show when the button is highlighted.
首先通过保留State Config
in 来选择您想要的图像作为默认状态Default
。有一个image
和一个background image
属性。设置完成后,您可以更改State Config
为Highlighted
并选择要在按钮突出显示时显示的图像。
NOTE: This is for xcode4.
注意:这是针对xcode4 的。
回答by utkal patel
when your view will appear then you have to initiate all the variable and UI property in view will appear method. (not necessary in all cases solution is only for your requirement)
当您的视图出现时,您必须启动视图中的所有变量和 UI 属性将出现方法。(并非在所有情况下都需要解决方案仅针对您的要求)
There you can set your button default state and image.
在那里您可以设置按钮的默认状态和图像。
-(void)viewWillAppear:(BOOL)animated
{
[m_Button2 setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[m_Button1 setSelected:NO];
...
}