1

I am trying to create a button represented by an image which whenever is pressed changes the image to the other one so that I can know which image is currently selected.

- (IBAction)imageWasPressed:(id)sender {
   UIImage *imageWork = [UIImage imageNamed:@"icn_work"];
NSData *data1 = UIImagePNGRepresentation(self.imageButton.currentImage);
NSData *data2 = UIImagePNGRepresentation(imageWork);

if (data1==data2){
    [self.imageButton setImage:[UIImage imageNamed:@"icn_personal"] forState:UIControlStateNormal];}
}

I have also tried this but it didn't work:

- (IBAction)imageWasPressed:(id)sender {
if ([[self.imageButton imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"icn_work"]]){
    [self.imageButton setImage:[UIImage imageNamed:@"icn_personal"] forState:UIControlStateNormal];}
}    

The line which changes the images works but I can't compare the two images. Any help would be much appreciated! Thank you!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Toma Radu-Petrescu
  • 2,152
  • 2
  • 23
  • 57
  • have you tried `[data1 isEqual:data2]`? – dalton_c Jul 21 '14 at 18:21
  • Also, as an aside, you probably shouldn't be comparing images to get this information. Keep a BOOL like, `if (self.personalSelected)` changing that when a button is selected instead. – dalton_c Jul 21 '14 at 18:23
  • @daltonclaybrook I've tried it before and it didn't work. It seems that it is working now, lol? Thanks a lot for your answer! – Toma Radu-Petrescu Jul 21 '14 at 18:25
  • Check this: http://stackoverflow.com/questions/11216167/objective-c-comparing-an-image-against-another-image-that-has-been-previously-s – arturdev Jul 21 '14 at 18:31

3 Answers3

2

This is rather unconventional approach, and I would recommend keeping track of your selection some other way.

But to answer the issue at hand, it does not work because you are comparing pointers, not data. data1 * will always be different to data2 *.

From the documentation: isEqualToData: Compares the receiving data object to otherData.

- (BOOL)isEqualToData:(NSData *)otherData
SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179
2

If you want to change button image regarding it's state you can assign different images for different states.

[self.imageButton setImage:image1 forState:UIControlStateNormal];
[self.imageButton setImage:image2 forState:UIControlStateHighlighted];
[self.imageButton setImage:image3 forState:UIControlStateSelected];

Since you can get button state and you know what image you set for the state you can get image as well.

modusCell
  • 13,151
  • 9
  • 53
  • 80
0
if ([data1 isEqualToData: data2])

instead of

if (data1==data2)