简体   繁体   中英

How to change the image of button with the help of tag?

How i can change the image on button when i have only tag of that button. for instance I have 20 buttons and tag is set 0 to 19. now in a response of some action i have the tag 5 of that button and now i want to change the image of that button. how could it possible? Please help

I think you can use it:

for (UIButton *button in self.view.subviews) {
        if (button.tag == 5) {
            [button setBackgroundImage:[UIImage imageNamed:@"new-imagepng"] forState:UIControlStateNormal];
        }
    }

But I didn't check it.

The following code gives you the button you are after ( superView refers to whatever view is holding your button):

UIButton *button5 = [superView viewWithTag:5];

Then you can amend the properties of the button as you see fit.

UIButton *button = (UIButton *)[myView viewWithTag:myTag];
[button setImage:... forState:...];

The myView variable is superview of the 20buttons. You can get UIButton object from the tag and can set image for your state.

Make the action of all buttons the same, say @(selector)buttonPressed: . Then in your handler do this:

-(void)buttonPressed:(id)sender {
  UIButton *button = (UIButton *) sender;
  int tag = button.tag; 
  // respond as you wish using tag... for example:
  UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"img%02d.png", tag]];
  [button setImage:image forState:UIControlStateNormal];
}

One more warning: better use integers 1 through 20 rather than 0 through 19. This way you avoid mistakes that might arise out of the fact that the default tag of every UIView is set to 0.

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