如何设置UIControlStateSelected的button图像
嗨,我想改变我的button后,我按下button,即button不应该改回到以前的形象。
但是,我无法这样做。 我的代码如下。 任何人都可以build议我点击button后,如何将图像更改为“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];
你提到过,你不想让图像改变回来,那么不必将其设置为突出显示或select的状态,而必须将其设置为状态UIControlStateNormal。
但是由于在按下button后需要它,所以必须捕捉button被按下的事件并将背景图像设置在那里。
希望它有帮助;)
方法1
我看到你正在使用代码来生成UIButton
。 使用Interface Builder更容易。 试试这个 – 在界面生成器(Xcode4)中,创buildbutton并打开右侧边栏。 之后,selectbutton,button的types为custom
。 之后在state config
,有各种状态,每个状态可以在image
设置image
。 希望这可以帮助…
方法2
如果你想使用代码来生成UIButton
(它击败了我为什么),那么你似乎做正确的事情。 你确定图像在你的包吗? 您没有包含图片扩展名(如.jpg等)
[_buttonConfirm setImage:[UIImage imageNamed:@"s.png"] forState:UIControlStateSelected ];
…做你想要的程序,而不是背景图片。 但是我认为如果可以的话,你应该遵循斯里卡尔的回答并使用接口生成器。