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

标签 ios objective-c uibutton

我有一个 UIButton,我正在为其成功设置背景图像。我想在用户点击它时更改背景图像(导航到下一个 View Controller )。不幸的是,背景不会因点击而改变。但是,当我点击并按住按钮时,它确实发生了变化,所以我很困惑。代码如下所示:

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

最佳答案

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

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

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

关于ios - UIButton 背景图像在点击时不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28389378/

相关文章:

objective-c - 用于 Objective-C 和 iOS 开发(XCode 除外)的 IDE

ios - 检查哪个 UIButton 被点击

ios - 在 ios 中使用 StoryBoard 的一个按钮和多个操作

ios - 当按钮是 iOS 中自定义单元格的 subview 时,如何动态更改按钮文本?

ios - Swift(iOS) 将 UIImage 数组插入 subview ?

ios - locationManager.location 始终为零

ios - UITapGestureRecognizer 不响应动画 subview

ios - 如何将一个SCNNode指向另一个SCNNode?

objective-c - 如何旋转 UIWebView 的内容?

objective-c - cocoa 为 os x 10.11 构建,支持 NSTouchbar