Checking UIButton Image

163 views Asked by At

I am trying to check some UIButton images to see if they are certain images. If they are, I want to set an NSString to a value but the value is always null. What am I doing wrong?

if ([self.firstButton.currentImage isEqual:[UIImage imageNamed:@"image"]]
    && [self.secondButton.currentImage isEqual:[UIImage imageNamed:@"another_image"]]
    && [self.thirdButton.currentImage isEqual:[UIImage imageNamed:@"another_image"]]
    && [self.fourthButton.currentImage isEqual:[UIImage imageNamed:@"another_image"]]
    && [self.fifthButton.currentImage isEqual:[UIImage imageNamed:@"another_image"]]) {
     self.myString = @"some string";
}

NSLog(@"My String: %@", self.myString);
2

There are 2 answers

0
Gopesh Gupta On BEST ANSWER

You can do like this

[[self.firstButton imageForState:UIControlStateNormal]isEqual:[UIImage imageNamed:@"image"]]

Try this one. This may help.

0
Cevaro On

Comparing image content isn't a trivial task and comparing handles to memory isn't reliable.

Try converting the images to NSData and compare those with each other. {

NSData * const firstButtonImageData = UIImagePNGRepresentation(self.firstButton.currentImage);
NSData * const secondButtonImageData = UIImagePNGRepresentation(self.secondButton.currentImage);
NSData * const myImageData = UIImagePNGRepresentation([UIImage imageNamed:@"image"]);
NSData * const anotherImageData = UIImagePNGRepresentation([UIImage imageNamed:@"another_image"]);

if ([firstButtonImageData isEqualToData:myImageData] &&
        [secondButtonImageData isEqualToData:anotherImageData])
{
    self.myString = @"some string";
}

NSLog(@"My String: %@", self.myString);