一尘不染

如何设置状态的UIButton背景颜色:UIControlState.Swift中突出显示

swift

我可以为按钮设置背景颜色,但无法确定如何为设置背景颜色 UIControlState.Highlighted。可能吗
还是我需要走这setBackgroundImage条路?


阅读 748

收藏
2020-07-07

共1个答案

一尘不染

如果有人停下来,如果您需要多次的话,另一种可能走的更容易的方法……我为UIButton写了一个简短的扩展,它工作得很好:

对于Swift 3

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControlState) {
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
        CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, forState: forState)
    }
}

对于Swift 4

extension UIButton {
    func setBackgroundColor(color: UIColor, forState: UIControl.State) {
        self.clipsToBounds = true  // add this to maintain corner radius
        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
        }
    }
}

您可以像使用它一样setBackgroundImage

yourButton.setBackgroundColor(color: UIColor.white, forState: UIControl.State.highlighted)
2020-07-07