UIButton 背景图像在点击时不会改变

UIButton background image not changing on tap

我有一个 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 做得太过了,但我想演示一下我已经尝试了所有方法:)

好吧,问题是一旦您停止点击按钮,按钮的背景图像将默认为您为 UIControlStateNormal 设置的任何背景图像。所以你需要做的是当你的按钮被点击时,在选择按钮后将 UIControlStateNormal 背景图像重置为你想要的任何图像。

问题是您只是在每个事件发生时才更改图像。当您点击并按住时,它会显示突出显示的图像。当您更改该状态时,它会恢复到正常状态并显示图像(正常背景图像)

您可以通过两种方式实现所需的行为:

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)

将按钮的selectedhighlighted属性设置为true

- (IBAction)buttonPressed:(UIButton *)button
{
   button.selected = YES;
}