0

我正在阅读一个看似很简单但无法让它工作的教程。目标是在使用 IB 创建的 UI 视图中有一个标签和一个按钮。标签应该是“Hello World”,当您单击按钮时,它会将文本更改为“Hello iPhone”。当我实现代码时,标签不会改变。当我调试时,我发现标签是“null”,但我不知道为什么......我真的很感谢你的帮助。

标签具有标签值“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"; 
}
4

3 回答 3

1

假设您在 ViewController 中。我不知道你的窗口属性是什么。此外,您应该对字符串使用“%@”。格式说明符

-(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";

}
于 2012-07-19T20:18:28.293 回答
0

Reading between the lines it sounds like your action method is not being fired.

You weren't explicit in saying how you knew the label text was blank, but can we assume that you did actually get the NSLog to output its results? If you didn't then I refer to my first sentence... Check that you have wired up your Button correctly in the Interface Builder, to point to an outlet action.

于 2012-07-19T20:13:31.683 回答
-1

在你的@interface 你应该有:

IBOutlet UILabel *label;

然后在您的 -(IBAction)buttonTapped 中:

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";
}
于 2012-07-19T20:06:48.567 回答