我创建一个按钮并将标题设置为“单击此处”。当我按下该按钮时,我想获得该按钮标题并记录下来。这是我的代码,我哪里错了?
-(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.
}
答案 0 :(得分:72)
您的displayvalue:方法应如下所示:
-(void)displayvalue:(id)sender {
UIButton *resultButton = (UIButton *)sender;
NSLog(@" The button's title is %@.", resultButton.currentTitle);
}
(请查看XCode中的文档,它会给你正确的答案。)
答案 1 :(得分:13)
-(void)displayvalue:(id)sender
{
UIButton *resultebutton= (UIButton*)sender;
NSLog(@"The button title is %@ ", resultebutton.titleLabel.text);
}
答案 2 :(得分:3)
我知道这是一个古老的问题,但这可能是解决这个问题的最佳方法。
NSLog(@"The button title is: %@", [sender currentTitle]);
修改强>
我刚刚意识到这取决于您已将接收参数设置为UIButton*
的事实。而不是使用默认id
,创建UIButton
对象并将(id)sender
投射到该按钮。剪掉中间人并将函数签名设置为
-(void)buttonPressed:(UIButton*)sender{
NSLog(@"Button title: %@",sender.currentTitle);
}
这有效地转换了函数参数
答案 3 :(得分:1)
-(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]);
}