Home > database >  Swift backgroundColor comparison not working
Swift backgroundColor comparison not working

Time:10-22

When programmatically adding background color to UIButton to system green sender.backgroundColor = UIColor.systemGreen it sets the backgroundColor to SystemGreen, yet when I check it with this if/else statement

if(sender.backgroundColor == UIColor.systemGreen)
{
   doSomething()
}
else 
{
   otherThing()
}

doSomething() is not called, and code goes to the else statement. Why?

CodePudding user response:

I tried this

Step 1: Set the background of UIButton in viewdidload

@IBOutlet weak var currentBtn: UIButton!
     
    override func viewDidLoad() {
        super.viewDidLoad()
        currentBtn.backgroundColor = UIColor.systemBrown
    }

step 2: compare the two colours with help of cgcolour in the button action, its works fine for me, please check your end too.

@IBAction func checkButton(_ sender: UIButton) {
        if let getColour = sender.backgroundColor, getColour.cgColor == UIColor.systemBrown.cgColor{
           print("comes here")
        }else {
            print("not here")
        }
    }
  • Related