简体   繁体   中英

How to find the correct UIButton object inside action

I'm using the code in this answer to generate a grid of buttons.

When a button is clicked I want to change the button image. So I need to do something like:

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

But I don't know how to assign toggleButton to the right button from the UI. I don't have an outlet for every button. Any ideas how I can do this?

If you are changing the same button that has been pressed, this should work:

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

This is because sender is the button that has been pressed.

Use the argument sender . sender is the object you committed the action on. So .. just cast it to UIButton and change the image

If you have not created outlet & action for every Button then even getting the subviews and comparing through isKindofClass will not solve the problem. You will have to assign a tag value to each button and you can cast the sender to UIButton and then determine the tag and change the image according to the tag. If you want to change the image of the button being pressed , you could simply change the image of sender as the pressed button is the latest.

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

in case image of pressed button has to be changed simply change the image , no need of if part and tag.

If you want to handle toggle switch on and off on dynamic UIButton, maintain the state in tag property as 0 or 1 and one important thing sender parameter always indicate that this is object on which action has been 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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM