objective-c 在事件处理程序中获取 UIButton 的标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/900867/
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
Getting title of UIButton in event handler
提问by Raju
I create a button and set title as "Click here". When I press that button I want to get that button title and log it. Here's my code, where am I going wrong?
我创建了一个按钮并将标题设置为“单击此处”。当我按下那个按钮时,我想得到那个按钮的标题并记录下来。这是我的代码,我哪里出错了?
-(void)clicketbutton {
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeCustom];
[mybutton setTitle:@"Click here" forState:UIControlStateNormal];
[mybutton addTarget:self
action:@selector(displayvalue:)forControlEvents:UIControlEventTouchUpInside];
}
-(void)displayvalue:(id)sender {
UIButton *resultebutton= [UIButton buttonWithType:UIButtonTypeCustom];
resultebutton=sender;// pls clear here.. my question here , it it possible or not. if possible how ?
NSLog(@" The buttontitile is %@ ", [resultebutton.Title] // here also.
}
回答by Harry Lachenmayer
Your displayvalue: method should look something like this:
您的 displayvalue: 方法应如下所示:
-(void)displayvalue:(id)sender {
UIButton *resultButton = (UIButton *)sender;
NSLog(@" The button's title is %@.", resultButton.currentTitle);
}
(Please check out the documentation in XCode, it would have given you the right answer.)
(请查看 XCode 中的文档,它会给您正确的答案。)
回答by Vaibhav Saran
-(void)displayvalue:(id)sender
{
UIButton *resultebutton= (UIButton*)sender;
NSLog(@"The button title is %@ ", resultebutton.titleLabel.text);
}
回答by mylogon
I know it's a bit of an old question, but this is probably the neatest way to resolve this one.
我知道这是一个老问题,但这可能是解决这个问题的最巧妙方法。
NSLog(@"The button title is: %@", [sender currentTitle]);
Edit
I've just realised that this is depending on the fact that you have set the receiving parameter to UIButton*. Rather than using the default id, creating a UIButtonobject and casting (id)senderto that button. Cut out the middle man and just set the function signature to
编辑
我刚刚意识到这取决于您已将接收参数设置为UIButton*. 而不是使用默认值id,而是创建一个UIButton对象并投射(id)sender到该按钮。去掉中间人,只需将函数签名设置为
-(void)buttonPressed:(UIButton*)sender{
NSLog(@"Button title: %@",sender.currentTitle);
}
This is effectively casting the function parameter
这有效地转换了函数参数
回答by iworld
-(void)clicketbutton {
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeCustom];
[mybutton setTitle:@"Click here" forState:UIControlStateNormal];
[mybutton addTarget:self
action:@selector(displayvalue:)forControlEvents:UIControlEventTouchUpInside];
}
-(void)displayvalue:(id)sender {
NSLog(@"The title is %@ ", [mybutton titleForState:UIControlStateNormal]);
}

