Ashish Verma Ashish Verma - 4 months ago 21
Swift Question

UIButton background color for highlighted/selected state issue

I've a

UIButton
and I've created an extension to add background color for different state.

I'm using the following code:

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)



My Problem is that it is not picking up proper
UIButton
background color and title color for highlighted/selected state.


Normal state
Highlighted state

Answer

I found the issue, UIButton was set to System.I simply changed it to Custom, it started working as expected.