在我的应用程序的某些时候,我有一个突出显示的UIButton(例如当用户有他的手指在按钮上),我需要改变背景颜色,而按钮是突出显示的(所以当用户的手指仍然在按钮上)。

我尝试了以下方法:

_button.backgroundColor = [UIColor redColor];

但这并不奏效。颜色保持不变。当按钮没有高亮显示时,我尝试了同一段代码,它工作得很好。我还尝试在改变颜色后调用-setNeedsDisplay,它没有任何效果。

如何强制按钮改变背景颜色?


当前回答

使用https://github.com/swordray/UIButtonSetBackgroundColorForState

使用CocoaPods添加到Podfile

pod "UIButtonSetBackgroundColorForState"

斯威夫特

button.setBackgroundColor(.red, forState: .highlighted)

objective - c

[button setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];

其他回答

试试tintColor:

_button.tintColor = [UIColor redColor];

如果你有一张图片,试试这个:

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

或者看看showsTouchWhenHighlighted是否足够。

为了解决这个问题,我创建了一个Category来处理UIButtons的backgroundColor状态: ButtonBackgroundColor-iOS

您可以将类别安装为pod。

易于与Objective-C一起使用

@property (nonatomic, strong) UIButton *myButton;

...

[self.myButton bbc_backgroundColorNormal:[UIColor redColor]
                 backgroundColorSelected:[UIColor blueColor]];

甚至更容易使用Swift:

import ButtonBackgroundColor

...

let myButton:UIButton = UIButton(type:.Custom)

myButton.bbc_backgroundColorNormal(UIColor.redColor(), backgroundColorSelected: UIColor.blueColor())

我建议您导入豆荚:

platform :ios, '8.0'
use_frameworks!

pod 'ButtonBackgroundColor', '~> 1.0'

使用use_frameworks !在你的Podfile中使你更容易使用Swift和objective-C。

重要的

我还写了一篇博客来提供更多的信息。

你可以使用这个类别添加方法setBackgroundColor:forState:

https://github.com/damienromito/UIButton-setBackgroundColor-forState-

一个更紧凑的解决方案(基于@aleksejs-mjaliks的答案):

Swift +四分之三的:

override var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? .lightGray : .white
    }
}

斯威夫特2:

override var highlighted: Bool {
    didSet {
        backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()
    }
}

如果你不想覆盖,这是一个更新版本的@timur-bernikowich的答案(Swift 4.2):

extension UIButton {
  func setBackgroundColor(_ color: UIColor, forState controlState: UIControl.State) {
    let colorImage = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in
      color.setFill()
      UIBezierPath(rect: CGRect(x: 0, y: 0, width: 1, height: 1)).fill()
    }
    setBackgroundImage(colorImage, for: controlState)
  }
}