动态创建的标签被覆盖

时间:2011-09-17 12:09:01

标签: iphone objective-c

我正在处理一个应用程序,其中我在一个函数中动态添加了5个标签。当我回想起相同的功能时,尽管在每次创建时都释放了标签,但是在先前创建的标签上覆盖了标签。

    for(int i = 1; i < [array count]; i++)
    {   
        CGRect lblframe = CGRectMake(count, ycord, width, height);
        UILabel *label = [[UILabel alloc] initWithFrame:lblframe];
        label.backgroundColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:17];
        label.textAlignment = UITextAlignmentCenter;
        label.textColor = [UIColor colorWithRed:(188/255.f) green:(149/255.f) blue:(88/255.f) alpha:1.0];;
        label.text = [arr objectAtIndex:i];

        count = count + xcord;
        [subcatScroll addSubview:label];           
        [label release];
   }

2 个答案:

答案 0 :(得分:5)

在for循环之前写下面的代码以获得您的要求:

for (id object in [subcatScroll subviews]) {

    [object removeFromSuperview];
}

答案 1 :(得分:0)

我不确定我是否完全跟随,如果我误解,请纠正我。 每次调用此函数时,都会添加许多新标签。因此,如果你第二次调用这个函数,假设'count','ycord','width'和'height'与第一个调用的值相对应,你显然是在同一个地方添加第二组标签作为第一个现在直接在彼此之上的人。你并没有“覆盖”旧标签,而是将第二组直接放在旧标签上。

在每个标签上调用“release”,仅表示您将retainCount减少1.此数字仅用于内存管理。这意味着如果您现在从视图中删除标签,则释放内存。

CGRect lblframe = CGRectMake(10.0, ycord, 200.0, 20.0);
UILabel *label = [[UILabel alloc] initWithFrame:lblframe];
NSLog(@"retainCount of label: %d", [label reatinCount]); // will print "1" since you called alloc
[self.view addSubview:label];
NSLog(@"retainCount of label: %d", [label reatinCount]); // will print "2" since adding to subview increases retaincount by one
[label release];
NSLog(@"retainCount of label: %d", [label reatinCount]); // will print "1" since you released
[label removeFromSuperview]; // will decrease retainCount of label to "0" and therefore free the memory

所以说你想从视图中删除以前创建的标签,你必须这样做。要么保留对它们的引用,要在每个引用上调用“removeFromSuperview”。

如果您在视图中添加标签的唯一内容,您也可以删除添加到其中的每个子视图,如下所示:

// remove old labels
for (UILabel *aLabel in [self.view subviews]) [aLabel removeFromSuperview];

NSArray *myArray = [NSArray arrayWithObjects:@"I", @"II", @"III", @"IV", nil];
for (int i=0; i<[myArray count]; i++) {
    float ycord = i*40.0;
    CGRect lblframe = CGRectMake(10.0, ycord, 200.0, 20.0);
    UILabel *label = [[UILabel alloc] initWithFrame:lblframe];
    label.backgroundColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:17];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor colorWithRed:(188/255.f) green:(149/255.f) blue:(88/255.f) alpha:1.0];;
    label.text = [myArray objectAtIndex:i];

    [self.view addSubview:label];
    [label release];
}

我希望这会有所帮助,但提供有关您尝试做的事情的更多信息可能会让您更轻松地为您提供帮助。

相关问题