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.
I found the issue, UIButton
was set to System.I simply changed it to Custom, it started working as expected.
Update 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)
}
}
Event Button Action Show Touch On Highlight
Swift 5, IOS 13+
extension UIButton {
func setBackgroundColor(_ color: UIColor, for forState: UIControl.State) {
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With