[英]How to update UILabel programmatically in iOS
我正面临着更新我的标签的问题..它不会删除旧的值,所以新的值会在旧的值之上..任何有关这方面的帮助将不胜感激..
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等。
在你的代码中,我不知道你的变量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];
如果您的视图中有其他标签,则可以将它们保存在数组中并仅删除它们
您需要调用setNeedsDisplay以便应用程序知道它已更改并重绘它。
- (void)setNeedsDisplay
您的updateLabels
方法实际上每次都会创建新的UILabel
控件,因此它们只会显示在“旧版本”之上。 我猜这不是你想要的,虽然如果我误解了你想要做的事情,那么道歉并不是很清楚。
如果我对此是正确的,可以在viewDidLoad
或类似内容中创建一次UILabel
控件。 然后在计时器触发时设置他们的.text
属性。
将标签的clearsContextBeforeDrawing属性设置为YES
你可以从nib和代码中设置它。
label.clearsContextBeforeDrawing = YES;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.