2016-07-25 110 views
9

我有一个UIButton,我创建了一个扩展来为不同的状态添加背景颜色。突出显示/选择状态问题的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) 

我的问题是,它不拾取高亮显示/选中状态正确UIButton背景颜色和标题的颜色。

Normal state Highlighted state

回答

39

我发现这个问题,UIButton设置为系统。我只是把它改成定制,它开始按预期工作。

+0

我有同样的问题,使它定制做伎俩。按下的状态是突出显示的,而不是我认为(选定)的内容:S。 – MQoder

0

当你的UIButton被选中。如果您专注于该按钮,则不会将该按钮突出显示为状态.Highlighted。如果未选中,则会按照您的意愿突出显示。因为它认为你的按钮中有背景图片,它将使用默认效果来突出显示图像。如果您想将状态更改为.Selected,则必须将UIButton的变量selected设置为true。

相关问题