jake9115 jake9115 - 2 months ago 4x
iOS Question

How to get a button's current image using imageForState?

I found a property called imageForState in xcode but am having trouble getting it to do what I want. When a button is pressed, I want to execute a block of code depending on the button's image.

- (IBAction)favButton:(UIButton *)sender {
NSString *currentImage = [sender imageForState:UIControlStateNormal];
if([currentImage isEqualToString:@"already_fav"])
// execute code

However, I am getting the error:

Incompatible pointer types initializing NSString _strong with an expression type of UIImage

Can someone please tell how to get around this?


I am sure that you are not able to compare a string with an image. There is a solution however. All you have to do is set the tag for the image you are wanting to compare, and set the tag of the image you are comparing to.

 image1.tag = 1;
 image.tag =1;

 if(image1.tag == image.tag) {
      // execute code

that should help, and I hope that it does.

SO, for this exercise, i'll show you. Change the NSString to a UIImage

 UIImage *currentImage = [sender imageForState:UIControlStateNormal];

 currentImage.tag = 1;
 wantedImage.tag = 1;

if(currentImage.tag == wantedImage.tag) {
   // do something

hopefully this helps you out :)