简体   繁体   English

如何借助标签更改按钮的图像?

[英]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. 例如,我有20个按钮,并且标签设置为0到19。现在响应某些操作,我具有该按钮的标签5,现在我想更改该按钮的图像。 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): 以下代码为您提供了所需的按钮( superView指的是按住按钮的任何视图):

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. myView变量是20个按钮的超级视图。 You can get UIButton object from the tag and can set image for your state. 您可以从标记中获取UIButton对象,并可以为您的状态设置图片。

Make the action of all buttons the same, say @(selector)buttonPressed: . 使所有按钮的action相同,例如@(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. 另一个警告:最好使用1到20的整数,而不是0到19的整数。这样可以避免由于每个UIView的默认tag都设置为0而引起的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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