Is there a way to compare button images in Swift/iOS

It can be done in following way:

   if let btnImage = sender.image(for: .normal),
        let Image = UIImage(named: "firstImage.png"), UIImagePNGRepresentation(btnImage) == UIImagePNGRepresentation(Image)
    {
        sender.setImage(UIImage(named:"secondImage.png"), for: .normal)

    }
   else 
    {
         sender.setImage( UIImage(named:"firstImage.png"), for: .normal)
    }

Matt Cooper's solution won't work in iOS 8 because Apple has changed how images are cached. You now need to use .isEqual

As in:

// assuming both button and newButton are UIImage instances
if button.currentImage!.isEqual(newButton) {
  ...

From Apple Docs:

As of iOS 8, you can no longer rely on pointer equality to compare cached UIImage objects as the caching mechanism may not return the same UIImage object, but will have cached image data separately. You must use isEqual: to correctly test for equality.

The downside of this is that it won't work in iOS 7! I don't know of a way that will work in both but I'm hoping there is, I'm searching for it myself :)


On iOS 13 @Matt Cooper's answer does not work, I'm not sure but other infos are included in the name of the image (maybe changes in the API since 2015), so my comparison always returns false:

UIImage: 0x28297e880 named (main: Icon-camera-alt) {20, 20}

I've used this in my case:

myButton.currentImage?.description.contains("camera-alt")

Updated for iOS 8 thanks to kakubei

UIButton has a property called currentImage, so use that to compare the images:

iOS 8+

if myCell.followButton.currentImage.isEqual(UIImage(named: "yourImageName")) {
    //do something here
}

iOS 7-

if (myCell.followButton.currentImage == UIImage(named: "yourImageName")) {
    //do something here
}

A better way to achieve this functionality would be to keep track of the button's selected state and change its image based on that. That would make it more flexible if you ever change the name of the image.

Tags:

Ios

Swift