UIButton背景颜色突出显示/select状态问题

我有一个UIButton ,我创build了一个扩展,为不同的状态添加背景颜色。

我使用下面的代码:

 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) 

我的问题是,它没有select适当的UIButton背景颜色和标题颜色突出显示/select状态。

正常状态 突出显示的状态

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

当你的UIButton被选中。 如果您专注于button,则不会将button突出显示为高亮显示。 如果未选中,则会按照您的意愿突出显示。 对于您的button中有背景图片,它将使用默认效果来突出显示图片。 如果要将状态更改为.Selected ,则必须将selectedUIButtonvariables设置为true。