如何设置和获取UIButtons的标签? [英] How do I set and get UIButtons' tag?

查看:69
本文介绍了如何设置和获取UIButtons的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I set a tag for a button programmatically?

稍后我想与标签进行比较

I later want to compare to tags for a conclusion

我已经尝试过了

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

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

but that just crashes the app.

还有其他想法吗?

推荐答案

您需要将发件人转换为UIButton:

You need to cast sender as a UIButton:

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

关于消息无法识别的选择器" ...

Regarding the message "unrecognized selector"...

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

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.

另外,您的原始代码"[sender标签]"也应该可以使用,但是要访问特定于按钮的属性,您仍然需要将其强制转换为UIButton.

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

这篇关于如何设置和获取UIButtons的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆