How to find the correct UIButton object inside an action

I use the code in this answer to create a button grid.

When I click a button, I want to change the image of the button. So I need to do something like:

- (void)buttonPressed:(id)sender { [toggleButton setImage:[UIImage imageNamed:toggleIsOn @"on.png"] forState:UIControlStateNormal]; } 

But I do not know how to assign toggleButton to the right button from the user interface. I have no way out for every button. Any ideas how I can do this?

+4
source share
4 answers

If you change the same button that was pressed, this should work:

 - (void)buttonPressed:(id)sender { [sender setImage:[UIImage imageNamed:toggleIsOn @"on.png"] forState:UIControlStateNormal]; } 

This is because the sender button is pressed.

+1
source

Use the sender argument. sender - the object on which you performed an action. So just drop it on UIButton and change the image

+1
source

If you want to enable and disable the toggle switch in a dynamic UIButton, save the state in tag as 0 or 1 , and one important sender parameter always indicates that this is the object whose action was taken.

 - (void)buttonPressed:(id)sender { UIButton* pressedButton=(UIButton *)sender; NSString* imageName=nil; if(pressedButton.tag==0){ imageName=@ "on.png"; pressedButton.tag=1; } else{ imageName=@ "off.png"; pressButton.tag=0; } [pressedButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal]; } 
+1
source

If you did not create an output and action for each button, then even obtaining sub-items and comparing with isKindofClass will not solve the problem. You will need to assign a tag value to each button, and you can send the sender to UIButton, and then define the tag and change the image to match the tag. If you want to change the image of the pressed button, you can simply change the image of the sender, since the pressed button is the last.

 if(((UIButton *)sender).tag==intvalue) { ((UIButton *)sender) setImage:[UIImage imageNamed:@"Your Image"]]; } 

in case of changing the image of the pressed button just change the image, it is not necessary if the part and tag.

0
source

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


All Articles