Swift: UIButton.currentImage is not working comparing image name

419 Views Asked by At

I'm trying to check the image name in the UIButton like this:

@IBAction func buttonTapped(_ sender: Any) {

    if xcodeButton.currentImage == UIImage(named: "xcode") {
        print("xcode image")
    }
}

But I have a break point in the if statement and this is the output:

po xcodeButton.currentImage
▿ Optional<UIImage>
  - some : <UIImage:0x6000011a93b0 named(main: xcode) {500, 500}>

but if I compare it

po xcodeButton.currentImage == UIImage(named: "xcode")
false

Any of you knows why the comparison is returning false? or how can compare the name of the image in UIButton?

I'll really appreciate your help.

2

There are 2 best solutions below

0
On BEST ANSWER

You should use isEqual(_:) From Docs scroll to Comparing Images section

let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage") 
if image1 != nil && image1!.isEqual(image2) {
   // Correct. This technique compares the image data correctly.
} 
if image1 == image2 {
   // Incorrect! Direct object comparisons may not work.
}
0
On

None of these solutions were working for me. So I used pngData to compare images:

let image1Data = UIImage(named: "MyImage")?.pngData()
let image2Data = UIImage(named: "MyImage")?.pngData()
if image1Data == image2Data {
   // It compares data correctly
}