Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I've looked around and I don't think there's a way to do this, but what I'm looking for is the ability to compare button images. I have a situation where I want to see if the button is set to a certain image before I change it. The pseudocode would be something like

if (myCell.followButton.image == UIImage(named: "")) {
//do something here
}
like image 457
pbush25 Avatar asked Mar 09 '15 03:03

pbush25


People also ask

How can I tell if two images are similar in Swift?

The isEqual(:) method is the only reliable way to determine whether two images contain the same image data. The image objects you create may be different from each other, even when you initialize them with the same cached image data.

How do I scale a button image in Swift?

Using storyboard, select the button, then in the size inspect click the dropdown on size just above Content inset. There is a list of sizes to select from, and this will adjust your image size(if you use system image). The default size is already set when you added the button on the storyboard to the View Controller.


2 Answers

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")
like image 136
Mehdi Chennoufi Avatar answered Sep 28 '22 01:09

Mehdi Chennoufi


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)
    }
like image 40
H S Progr Avatar answered Sep 28 '22 01:09

H S Progr