0

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.

user2924482
  • 8,380
  • 23
  • 89
  • 173

2 Answers2

1

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.
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

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
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253