如何在iOS中以编程方式更新UILabel

我正在更新我的标签面临一个问题..它不会删除旧的价值,所以新的价值观上的旧的..任何帮助将不胜感激..

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateLabels) userInfo:nil repeats:YES]; -(void) updateLabels{ for (GraphView *graph in arr){ // retrieve the graph values valLabel = [[UILabel alloc] initWithFrame:CGRectMake(i * 200, 0, 90, 100)]; valLabel.textColor = [UIColor whiteColor]; valLabel.backgroundColor = [UIColor clearColor]; valLabel.text = [NSString stringWithFormat:@"Value: %f", x]; i++; } } 

如果您设置标签的文本,则不需要调用setNeedsDisplay或clearContext等。

在你的代码中,我不知道你的variablesi和x是什么?

主要的问题是你在你的视图上创build和添加新的标签。 当您调用updateLabels方法时,可能会导致内存泄漏 。 只要你有n次标签重叠。

在创build和添加新标签之前,您需要删除标签,或者您可以重复使用已有的标签。 要重复使用标签,您需要将它们保存到数组中并更新文本。

如果你想创build新的标签,那么你可以这样做,除非你在视图中有其他标签

 -(void) updateLabels{ // remove all labels in your view for (UIView *labelView in self.view.subviews) { if ([labelView isKindOfClass:[UILabel class]]) { [labelView removeFromSuperview]; } for (GraphView *graph in arr){ // retrieve the graph values valLabel = [[UILabel alloc] initWithFrame:CGRectMake(i * 200, 0, 90, 100)]; valLabel.textColor = [UIColor whiteColor]; valLabel.backgroundColor = [UIColor clearColor]; valLabel.text = [NSString stringWithFormat:@"Value: %f", x]; i++; } } 

当你创build这样的新标签时,你需要把它们作为子视图添加到你的视图中

 [self.view addSubview: valLabel]; 

如果你的视图中有其他标签,那么你可以将它们保存在一个数组中,然后移除它们

你需要调用setNeedsDisplay,以便应用程序知道它已经改变并重绘它。

 - (void)setNeedsDisplay 

你的updateLabels方法实际上是每次创build新的UILabel控件,所以它们只会出现在“旧的”之上。 我猜这不是你想要的,但是如果我误解了你正在做的事情,那么不太清楚,所以我很抱歉。

如果我对这是正确的,创build你的UILabel控件只是一次,也许在你的viewDidLoad或类似的。 然后,只要设置他们的.text属性,当你的计时器激发。

将标签的clearsContextBeforeDrawing属性设置为YES

你可以从nib和代码中设置它。

 label.clearsContextBeforeDrawing = YES;