如果您设置标签的文本,则不需要调用 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];
如果视图中有其他标签,则可以将它们保存在数组中并仅删除它们