如何获取操作中按钮的名称?
我有一个名为“开始”的按钮,我想在方法中知道它的名称是什么,但我不太确定该怎么做。这是按钮调用的方法。
-(IBAction) startMotion: (id)sender {
UIButton * buttonName = (UIButton *) sender;
NSLog(@"Button Name: %@", buttonName.currentTitle);
}
NSLog 打印
按钮名称:(空)
I have a button named start and I want to know in the method that it calls what it's name is and I'm not really sure how to do it. This is the method the button calls.
-(IBAction) startMotion: (id)sender {
UIButton * buttonName = (UIButton *) sender;
NSLog(@"Button Name: %@", buttonName.currentTitle);
}
The NSLog prints
Button Name: (null)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以通过
和 来设置按钮的标题(currentTitle 是只读的,可能为 nil):
顺便说一句,如果你只是想区分多个按钮,你可以设置 tag 属性(整数值)按钮。
另外,检查您的 viewController 类中是否将按钮指定为 IBOutlet,以及它是否在 Interface Builder 中作为插座正确连接?
You can set the title of the button through
and to get the title (currentTitle is read-only and may be nil):
BTW, if you just want to differentiate multiple buttons, you can just set the tag property (an integer value) of the buttons.
Also, check if you have the button specified as an IBOutlet in your viewController class, and is it connected properly as an outlet in Interface Builder?
我宁愿设置某个标签并比较标签值,而不是读取按钮的标题,因为您可以本地化按钮标题可能不同的应用程序。
I would rather set a certain Tag and compare the tag value rather than reading the title of the button since you have possibility to localize your app where button titles will possibly be different.
我在 Interface Builder 中使用了错误的属性。我在 Interface Builder 中使用了按钮的 name 属性,而不是按钮设置中的 title 属性。
I was using the wrong property in Interface Builder.I was using name property of button in Interface Builder instead of the title property from the button settings.