如何在iOS中以编程方式更新UILabel [英] How to update UILabel programmatically in iOS

查看:86
本文介绍了如何在iOS中以编程方式更新UILabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在更新标签时遇到问题..它不会删除旧值,因此新值会在旧值的基础上..对此提供的任何帮助将不胜感激..

I am facing a problem with updating my labels.. it doesn't remove the old values so new values go on top of old ones.. any help with this will be appreciated..

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等.

If you set the text of your label you do not need to call setNeedsDisplay or clearContext etc.

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

In your code, I do not know what are your variables i and x?

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

The main problem is that you are creating and adding new labels on your view. When you call updateLabels method, may cause a Memory leak. Simply you have n times labels overlapped.

您需要先删除标签,然后再创建和添加新标签,或者可以重复使用已有的标签.要重用标签,您需要将它们保存到数组中并更新文本.

You need to remove the labels before you create and add new labels or you can reuse which you already have. To reuse your labels you need to save them to an array and update texts.

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

If you want to create new labels then you can do like this unless you have other labels in your view

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

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

When you create new labels like this you need to add them to your view as subview

[self.view addSubview: valLabel];

如果视图中还有其他标签,则可以将它们保存在数组中并仅将其删除

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

这篇关于如何在iOS中以编程方式更新UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆