ios 如何设置和获取 UIButtons 的标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2459570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:00:35  来源:igfitidea点击:

How do I set and get UIButtons' tag?

iosobjective-c

提问by Sam Jarman

How do I set a tag for a button programmatically?

如何以编程方式为按钮设置标签?

I later want to compare to tags for a conclusion

稍后我想与标签进行比较以得出结论

I've tried this

我试过这个

-(IBAction)buttonPressed:(id)sender{
    NSLog(@"%d", [sender tag]);
}

but that just crashes the app.

但这只会使应用程序崩溃。

Any other ideas?

还有其他想法吗?

回答by

You need to cast sender as a UIButton:

您需要将 sender 转换为 UIButton:

-(IBAction)buttonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(@"%d", [button tag]);
}

Edit: Regarding the message "unrecognized selector"...

编辑:关于消息“无法识别的选择器”...

Based on your error message, it's not able to call the buttonPressed method in the first place. Notice in the error message it is looking for "buttonPressed" (no colon at end) but the method is named "buttonPressed:". If you are setting the button target in code, make sure the selector is set to buttonPressed: instead of just buttonPressed. If you are setting the target in IB, the xib may be out of sync with the code.

根据您的错误消息,它首先无法调用 buttonPressed 方法。请注意,在错误消息中,它正在寻找“buttonPressed”(末尾没有冒号),但该方法名为“buttonPressed:”。如果您在代码中设置按钮目标,请确保选择器设置为 buttonPressed: 而不仅仅是 buttonPressed。如果您在 IB 中设置目标,则 xib 可能与代码不同步。

Also, your original code "[sender tag]" should also work but to access button-specific properties, you'll still need to cast it to UIButton.

此外,您的原始代码“[sender tag]”也应该可以使用,但要访问特定于按钮的属性,您仍然需要将其转换为 UIButton。

回答by timv

I know this is an old question and been answered many a time in other questions, but it came up in a google search as second from the top. So, here is the answer to why it was crashing. Change it to 'button.tag'

我知道这是一个老问题,并且在其他问题中被多次回答,但它在谷歌搜索中排在第二位。所以,这是它崩溃的原因的答案。将其更改为“button.tag”

-(void)myMethod
{
   UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
   [theButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];

    theButton.tag = i;//or whatever value you want.  In my case it was in a forloop

}

-(void)buttonPressed:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSLog(@"%d", button.tag);
}

回答by Kaveh Vejdani

No need for casting. This should work:

不需要铸造。这应该有效:

-(IBAction)buttonPressed:(UIButton*)sender
{
NSLog(@"%d", [sender tag]);
}