How to change the background color of a UIButton w

2019-01-01 09:53发布

At some point in my app I have a highlighted UIButton (for example when a user has his finger on the button) and I need to change the background color while the button is highlighted (so while the finger of the user is still on the button).

I tried the following:

_button.backgroundColor = [UIColor redColor];

But it is not working. The color remains the same. I tried the same piece of code when the button is not highlighted and it works fine. I also tried calling -setNeedsDisplay after changing the color, it didn't have any effect.

How to force the button to change the background color?

26条回答
梦该遗忘
2楼-- · 2019-01-01 10:44

Swift 3:

extension UIButton {
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x:0.0,y:0.0,width: 1.0,height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        context!.setFillColor(color.cgColor)
        context!.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }

    func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
        self.setBackgroundImage(imageWithColor(color: color), for: state)
    }
}
查看更多
余生请多指教
3楼-- · 2019-01-01 10:45

There is no need to override highlighted as computed property. You can use property observer to trigger background color change:

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

Swift 4

override open var isHighlighted: Bool {
    didSet {
        backgroundColor = isHighlighted ? UIColor.lightGray : UIColor.white
    }
}
查看更多
登录 后发表回答