0

我有一个标签,内容为

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(65,50,200,50)]; // RectMake(xPos,yPos,Max Width I want, is just a container value);

NSString *test=@"I am thinking of a number between 1 and 100.  What is it?";

testLabel.font = [UIFont systemFontOfSize:25];
testLabel.textAlignment = NSTextAlignmentCenter;
testLabel.text = test;
testLabel.numberOfLines = 0; //will wrap text in new line
[testLabel sizeToFit];

[self.view addSubview:testLabel];

在这个 ViewController.m 页面的末尾,我在用户提交字段值后按下了一个按钮:

- (IBAction)guessNow:(id)sender {


self.usersGuess = self.guessNumberField.text;


NSString *guessString = self.usersGuess;

if ([guessString length] == 0) {

    guessString = @"Really No Guess? Try Again.";

}

   //_testLabel.text = @""; attempting to clear out label when user submits the value
NSString *guessReply = [[NSString alloc] initWithFormat:@"Good try but %@ is not the answer!", guessString];

self.testLabel.text = guessReply;


}

问题是当用户在字段中输入值并点击猜测按钮时,答案会显示在初始字段值后面。这是一个屏幕截图:

在此处输入图像描述

如何清除初始消息以便只显示回复?

4

3 回答 3

0

看起来你必须分开 UILabel。在您的 viewDidLoad 方法中,您正在初始化新的 UILabel,设置其属性,然后将其添加到 self.view.subviews 但在guessNow: 方法中,您将字符串设置为 self.testLabel.text 属性,这与 UILabel 不同!您应该将 viewDidLoad 方法更改为:

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

self.testLabel =[[UILabel alloc] initWithFrame:CGRectMake(65,50,200,50)];

NSString *test=@"I am thinking of a number between 1 and 100.  What is it?";

self.testLabel.font = [UIFont systemFontOfSize:25];
self.testLabel.textAlignment = NSTextAlignmentCenter;
self.testLabel.text = test;
self.testLabel.numberOfLines = 0; //will wrap text in new line
[self.testLabel sizeToFit];

[self.view addSubview:self.testLabel];

如果您的 self.testLabel 是 IBOutlet 连接到 Storyboard 中的 UILabel,那么您应该在代码中省略这两行:

self.testLabel =[[UILabel alloc] initWithFrame:CGRectMake(65,50,200,50)];
...
...
...
[self.view addSubview:self.testLabel];
于 2013-10-07T19:37:05.330 回答
0

转到界面生成器。按住 Ctrl 按钮单击按钮(将处理清除文本的按钮)并拖动到您的实现视图控制器。将出现一个小窗口,从下拉菜单中显示 Touch Up 并命名方法,然后点击 Enter。

将创建一个空方法。里面的明文:

- (IBAction)clearText:(id)sender {
     self.testLabel.text = @"";
}
于 2013-10-07T18:59:34.290 回答
0

这里真正的问题是你没有正确地重用标签......说明和猜测应该写在同一个标​​签中。(无需将其重新添加到子视图中)您可以简单地使用 self.labelname.text=@"newLabel"。

您提供的代码与结果不匹配...

于 2013-10-07T19:09:22.173 回答