3

我在更新标签时遇到了问题。它不会删除旧值,因此新值会放在旧值之上。任何对此的帮助将不胜感激。

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++;
    }        
}
4

4 回答 4

5

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

在您的代码中,我不知道您的变量 i 和 x 是什么?

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

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

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

-(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++;
}        
}

当您创建这样的新标签时,您需要将它们作为子视图添加到您的视图中

[self.view addSubview: valLabel];

if you have other labels in your view then you can save them in an array and remove just them

于 2012-08-09T14:27:51.923 回答
2

您需要调用 setNeedsDisplay 以便应用程序知道它已更改并重绘它。

- (void)setNeedsDisplay
于 2012-08-09T13:42:59.403 回答
2

您的updateLabels方法实际上是UILabel每次都创建新控件,因此它们只会出现在旧控件的“之上”。我猜这不是你想要的,尽管如果我误解了你想要做的事情,这并不完全清楚,所以很抱歉。

如果我是正确的,请在您的或类似的地方创建UILabel一次您的控件。viewDidLoad然后.text在计时器触发时设置它们的属性。

于 2012-08-09T14:01:34.160 回答
1

将标签的 clearsContextBeforeDrawing 属性设置为 YES

您可以从 nib 和代码中进行设置。

label.clearsContextBeforeDrawing = YES;
于 2012-08-09T14:06:42.020 回答