25

我创建一个按钮并将标题设置为“单击此处”。当我按下该按钮时,我想获取该按钮标题并记录它。这是我的代码,我哪里出错了?

-(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.
}
4

4 回答 4

72

您的 displayvalue: 方法应如下所示:

-(void)displayvalue:(id)sender {       
    UIButton *resultButton = (UIButton *)sender;
    NSLog(@" The button's title is %@.",  resultButton.currentTitle);
}

(请查看 XCode 中的文档,它会给您正确的答案。)

于 2009-05-24T22:01:45.103 回答
13
-(void)displayvalue:(id)sender 
{
    UIButton *resultebutton= (UIButton*)sender;
    NSLog(@"The button title is %@ ", resultebutton.titleLabel.text);
}
于 2012-04-04T12:12:02.917 回答
3

我知道这是一个老问题,但这可能是解决这个问题的最巧妙方法。

NSLog(@"The button title is: %@", [sender currentTitle]);        

编辑
我刚刚意识到这取决于您已将接收参数设置为UIButton*. 而不是使用默认值id,而是创建一个UIButton对象并投射(id)sender到该按钮。去掉中间人,只需将函数签名设置为

-(void)buttonPressed:(UIButton*)sender{
  NSLog(@"Button title: %@",sender.currentTitle);
}  

这有效地转换了函数参数

于 2015-03-11T23:43:47.857 回答
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]);

}
于 2014-11-14T10:39:02.167 回答