使用viewdidappear更新程序化uilabel的正确方法

时间:2012-01-28 01:47:47

标签: iphone objective-c ios dynamic uilabel

每次加载此选项卡而不是更新动态标签时,它都会在其上写入一个全新的标签。我需要在此代码中放置什么,以便更新它或清除动态标签,然后放入新标签。我觉得它可能只是一个简单的一行修复。以下是代码的简化版本:

- (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:YES];
        goalArray = [[NSMutableArray alloc] init];
        NSURL *url = [NSURL URLWithString:@"http://localhost/goal.php"];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request setPostValue:test forKey:@"name"];
        [request setDelegate:self];
        [request startAsynchronous];         
    }
    - (void)requestFinished:(ASIFormDataRequest *)request
    {
       ...
            for (id myArrayElement in goalArray) 
            {
                NSLog(@"y value:%i", yValue);
                UILabel *label =  [[UILabel alloc] initWithFrame: CGRectMake(0, yValue, 80, 44)];
                label.font = [UIFont systemFontOfSize:12];
                label.textColor = [UIColor blackColor];
                label.backgroundColor = [UIColor clearColor];
                label.text = myArrayElement;
                [self.view addSubview:label];
                yValue += 44;
            } 
        }

1 个答案:

答案 0 :(得分:0)

在requestFinished中:在for循环之前,添加:

for ( UIView *die in [self subviews]) {   // clear out previous label
    if ( die.tag == 123 ) {
       [die removeFromSuperview];
    }
}

然后在for循环内添加:

label.tag = 123;  //doesn't have to be 123, as long as it's an int that matches the one above.