突出显示/选定状态问题的UIButton背景颜色

Ash*_*rma 18 uibutton ios swift

我有一个UIButton,我已经创建了一个扩展,为不同的状态添加背景颜色.

我正在使用以下代码:

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


// Set Button Title and background color for different states
    self.donateButton.setBackgroundColor(UIColor.redColor(), forState: .Normal)
    self.donateButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
    self.donateButton.setBackgroundColor(UIColor.greenColor(), forState: .Highlighted)
    self.donateButton.setTitleColor(UIColor.whiteColor(), forState: .Highlighted)
    self.donateButton.setBackgroundColor(UIColor.greenColor(), forState: .Selected)
    self.donateButton.setTitleColor(UIColor.whiteColor(), forState: .Selected)
Run Code Online (Sandbox Code Playgroud)

我的问题是它没有UIButton为突出显示/选择状态选择适当的背景颜色和标题颜色.

正常状态 突出状态

Ash*_*rma 67

我发现问题,UIButton设置为System.我只是将其更改为Custom,它开始按预期工作.

  • 我有同样的问题,让它自定义就行了。按下状态是突出显示的,而不是我认为的(选择的):S。 (2认同)

Puj*_*ono 5

更新Swift 4

extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControlState) {

        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        self.setBackgroundImage(colorImage, for: forState)
    }

}
Run Code Online (Sandbox Code Playgroud)

事件按钮动作显示触摸亮点