2009-05-23 51 views
25

我創建一個按鈕並將標題設置爲「單擊此處」。當我按下那個按鈕時,我想獲得那個按鈕標題並記錄下來。這是我的代碼,我哪裏錯了?在事件處理程序中獲取UIButton的標題

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

回答

72

你displayvalue:方法應該是這個樣子:

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

(請查看Xcode中的文檔,它會給你正確的答案)

+1

很好的歡呼聲 – 2011-04-15 08:31:10

13
-(void)displayvalue:(id)sender 
{ 
    UIButton *resultebutton= (UIButton*)sender; 
    NSLog(@"The button title is %@ ", resultebutton.titleLabel.text); 
} 
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]); 

} 
+1

我不認爲這會在所有的工作。爲了使它工作,mybutton需要是一個實例變量,但是你也需要在`-clicketbutton`中將該按鈕分配給實例變量 - 目前該方法使用的是局部變量。換句話說,`mybutton`在你的兩種方法中代表了不同的東西。 – 2015-03-11 23:49:04

3

我知道這是一個老問題,但這可能是解決這個問題的最好方法。

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

編輯
我剛剛纔知道這是根據事實,你已接收參數設置爲UIButton*。而不是使用默認的id,創建一個UIButton對象並將(id)sender轉換爲該按鈕。切出的中間人,只是設置函數簽名

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

這是有效的鑄造性能參數