如何为UIControlStateSelected设置按钮图像

Zhe*_*hen 1 objective-c uibutton uicontrol ios

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

但是,我无法这样做.我的代码如下.任何人都可以建议我在点击按钮后如何将图像更改为"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];
Run Code Online (Sandbox Code Playgroud)

Sri*_*aju 6

方法1

我看到你正在使用代码生成UIButton.使用"界面"构建器更容易.试试这个 - 在界面构建器(Xcode4)中,创建按钮并打开右侧边栏.之后选择按钮,按钮类型为custom.在此之后state config,有各种状态,您可以为每个州设置图像image.希望这可以帮助...

在此输入图像描述

方法2

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