如何设置UIControlState Selected的按钮图像

时间:2011-08-21 05:10:18

标签: objective-c ios uibutton uicontrol

嗨我想在按下按钮后改变按钮的背景,即按钮不应该变回上一张图像。

但是,我无法这样做。我的代码如下。任何人都可以建议我在点击按钮后如何将图像更改为“custom_button_highlight”?

UIImage *buttonImageNormal = [UIImage imageNamed:@"custom_button"];
UIImage *stretchableButtonImageNormal = [buttonImageNormal
                                         stretchableImageWithLeftCapWidth:12 topCapHeight:0];

UIImage *buttonImagePressed = [UIImage imageNamed:@"custom_button_highlight"];
UIImage *stretchableButtonImagePressed = [buttonImagePressed
                                          stretchableImageWithLeftCapWidth:12 topCapHeight:0];

button.titleLabel.font = [UIFont boldSystemFontOfSize:14];
[button setBackgroundImage:stretchableButtonImageNormal
                  forState:UIControlStateNormal];

[button setBackgroundImage:stretchableButtonImagePressed
                  forState:UIControlStateHighlighted];

[button setBackgroundImage:stretchableButtonImagePressed
                  forState:UIControlStateSelected];

3 个答案:

答案 0 :(得分:6)

<强>方法1

我发现您使用代码生成UIButton。使用“界面”构建器更容易。试试这个 - 在界面构建器(Xcode4)中,创建按钮&amp;打开右侧边栏。之后选择按钮,&amp;按钮的类型为custom。在state config之后,有各种状态,对于每个州,您可以在image中设置图像。希望这会有所帮助...

enter image description here

<强>方法2

如果你想使用代码来生成UIButton(这比我好),那么你似乎正在做正确的事情。你确定你的包中有图片吗?您没有包含图片扩展名(如.jpg等)

答案 1 :(得分:1)

你提到过,你不希望图像改变回来...... 然后,不必将其设置为突出显示或选择的状态,而是必须将其设置为状态UIControlStateNormal。

但是因为你在按下它之后需要它,你必须抓住你的按钮被按下的事件并在那里设置背景图像。

希望它有所帮助;)

答案 2 :(得分:0)

[_buttonConfirm setImage:[UIImage imageNamed:@"s.png"] forState:UIControlStateSelected ];

...以编程方式执行您想要的操作,而不是背景图像。但我认为你应该遵循Srikar的答案并尽可能使用界面构建器。