我有一个UIButton,我正在成功设置背景图像。我想在用户点击背景图像时(导航到下一个视图控制器)更改背景图像。不幸的是,水龙头的背景并没有改变。但是,当我点击并按住按钮时 会发生变化,所以我很困惑。代码如下所示:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x_offset, y_offset, width, BUTTON_HEIGHT)];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor whiteColor];
UIImage *buttonImage = [[UIImage imageNamed:@"main_button"]
resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
UIImage *pressedbuttonImage = [[UIImage imageNamed:@"main_button_pressed"]
resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateHighlighted];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateApplication];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateDisabled];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateReserved];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateSelected];
return button;
我知道我用UIControlStates过度了,但我想演示我已经尝试过所有这些:)
答案 0 :(得分:2)
问题是您只在每个事件发生时更改图像。当您点按并按住它时,将显示突出显示的图像。当您更改该状态时,它将恢复为正常状态并显示图像(正常背景图像)
您可以通过两种方式实现所需的行为:
<强> 1)强>
在IBAction
中,更改普通按钮图片。
- (IBAction)buttonPressed:(UIButton *)button
{
UIImage *pressedbuttonImage = [[UIImage imageNamed:@"main_button_pressed"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
[button setBackgroundImage:pressedbuttonImage forState:UIControlStateNormal];
}
<强> 2)强>
将按钮的selected
或highlighted
属性设置为true
- (IBAction)buttonPressed:(UIButton *)button
{
button.selected = YES;
}
答案 1 :(得分:0)
问题是,一旦你停止点击按钮,按钮的背景图像将默认为你为UIControlStateNormal设置的任何背景图像。因此,您需要做的是点击按钮时,在选择按钮后将UIControlStateNormal背景图像重置为您想要的任何图像。