Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 388
Ashish Verma Avatar asked Jul 25 '16 07:07

Ashish Verma


3 Answers

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

like image 159
Ashish Verma Avatar answered Nov 06 '22 21:11

Ashish Verma


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

like image 5
Puji Wahono Avatar answered Nov 06 '22 19:11

Puji Wahono


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

}
like image 1
Mike Zriel Avatar answered Nov 06 '22 19:11

Mike Zriel