2012-07-19 44 views
0

我正在瀏覽一個看起來非常簡單,但無法讓它工作的教程。目標是在UI視圖中使用IB創建一個標籤和一個按鈕。該標籤應該說「Hello World」,並且當您單擊該按鈕時,它會將文本更改爲「Hello iPhone」。當我實現代碼時,標籤不會改變。當我調試時,我發現標籤是「null」,但我無法弄清楚爲什麼......我真的很感謝你對此的幫助。新手xcode:UILabel爲空,但它不是

標籤的標籤值爲「55」。

我的代碼如下所示: 在接口文件:

-(IBAction)buttonTapped; 
主文件

-(IBAction)buttonTapped{ 
    UILabel *label = (UILabel*) [window viewWithTag:55]; 
    NSLog(@"The label's text is %s",label.text); //my debug statement 

    if([label.text isEqualToString:@"Hello World"]) 
     label.text = @"Hello iPhone"; 
    else 
     label.text = @"Hello World"; 
} 
+0

此標籤是在故事板中設置還是在代碼中創建的? – 8vius 2012-07-19 20:02:43

回答

-1
在@interface

你應該有:

IBOutlet UILabel *label; 

然後在你的 - (IBAction)按鈕彈出:

NSLog(@"The label's text is %s",label.text); //my debug statement 

if([label.text isEqualToString:@"Hello World"]) 
     label.text = @"Hello iPhone"; 
else 
     label.text = @"Hello World"; 
} 
0

在行之間讀取它聽起來像您的操作方法沒有被解僱。

你沒有明確地說出你是如何知道標籤文本是空白的,但我們可以假設你確實得到了NSLog輸出結果嗎?如果你沒有,那麼我參考我的第一句話......檢查你是否已經在界面生成器中正確連接了你的按鈕,以指向插座動作。

1

假設你在一個ViewController中。我不知道你的窗口屬性是什麼。你也應該使用「%@」作爲字符串。 Format Specifiers

-(IBAction) buttonTapped:(UIButton*)sender{  
    UILabel *label = (UILabel*) [self.view viewWithTag:55]; 
    NSLog(@"The label's text is %@",label.text); //my debug statement 

    if([label.text isEqualToString:@"Hello World"]) 
     label.text = @"Hello iPhone"; 
    else 
     label.text = @"Hello World"; 

} 
相關問題