How to get current button image using imageForState?

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

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

However, I get the error message:

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

Can anyone tell me how to get around this?

+4
source share
4 answers

I am sure that you cannot compare a string with an image. However, there is a solution. All you have to do is set the tag for the image you want to compare and set the tag for the image you are comparing.

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

which should help, and I hope he does.

SO, for this exercise I will show you. Change NSString to UIImage

  UIImage *currentImage = [sender imageForState:UIControlStateNormal]; currentImage.tag = 1; wantedImage.tag = 1; if(currentImage.tag == wantedImage.tag) { // do something } 

hope this helps you :)

+9
source

When you create a UIImage, it is just an image and has no string binding. The name is not carried by the UIImage.

If it were me (and this is not the only solution, just another suggestion), I would create separate UIImage objects (depending on how much we say here), since this should be checked, but the lines should not.

For instance:

 UIImage *image1 = [UIImage imageNamed:@"randomName"]; UIImage *image2 = [UIImage imageNamed:@"anotherRandomName"]; [myButton setImage:image2 forState:UIControlStateNormal]; if ([myButton imageForState:UIControlStateNormal] == image1) { NSLog(@"The button shows image 1 for normal state"); } else if ([myButton imageForState:UIControlStateNormal] == image2) { NSLog(@"The button shows image 2 for normal state"); } else { NSLog(@"Error!!!!!!! :D"); } 
+4
source

you cannot save the image as a string

try

UIImage *currentImage = [sender imageForState:UIControlStateNormal];

than you can check:

if(currentImage == [UIImage imageNamed:@"already_fav"])

+1
source

I did this to switch the / noSound sound to the button:

 - (IBAction)soundAction:(id)sender { UIImage *sound = [UIImage imageNamed:@"sound"]; UIImage *noSound = [UIImage imageNamed:@"noSound"]; if ([[sender currentImage] isEqual:sound]) { NSLog(@"IF SOUND IMAGE"); [sender setImage:noSound forState:UIControlStateNormal]; //your code } else if([[sender currentImage] isEqual:noSound]) { NSLog(@"IF NO SOUND IMAGE"); [sender setImage:sound forState:UIControlStateNormal]; //your code } } 
+1
source

Source: https://habr.com/ru/post/1485311/


All Articles