【问题标题】:UIButton background image not changing on tapUIButton背景图像在点击时不会改变
【发布时间】:2015-02-08 00:57:52
【问题描述】:

我有一个 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 上做得过火了,但我想演示一下我已经全部尝试过了:)

【问题讨论】:

    标签: ios objective-c uibutton


    【解决方案1】:

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

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

    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;
    }
    

    【讨论】:

    • 您的第一种方法有效 - 尽管我必须为 UIControlEventTouchDown 和 UIControlEventTouchUpOutside 编写一个处理程序 - 如果用户将手指从按钮上移开,后者会重置图像。幸运的是,我有一个帮助方法来构建我的按钮,所以我不必在任何地方添加这些代码行:)
    【解决方案2】:

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

    【讨论】:

    • 你是说它变化太快让我看不到吗?
    • 您找到解决问题的方法了吗,因为我现在也遇到了同样的问题。我也认为它正在快速变化,我们看不到变化。
    猜你喜欢
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多