UIScrollView - 添加/删除标签

时间:2009-05-29 16:14:50

标签: iphone cocoa-touch uiscrollview uilabel

我正在尝试将UILabel添加/删除到ScrollView。添加发生得很好,但在添加新标签之前,我似乎无法删除标签。任何人都可以对这种情况有所了解吗?

-(void)setMessage:(MessageData *)m{

    //Attempting to remove any previous labels

    iPhone_PNPAppDelegate *mainDelegate = (iPhone_PNPAppDelegate *)[[UIApplication sharedApplication] delegate];
    UILabel *l;
    for (NSInteger i=0; i<[[scrollView subviews] count]; i++){
        l=[[scrollView subviews] objectAtIndex:0];
        [l removeFromSuperview];
        l=nil;
    }

    //Adding my new Labels

    CGPoint pt=CGPointMake(5,5);
    if ([[[mainDelegate messageFieldCaptions] objectAtIndex:0] length]>0){
        NSArray *p=[[[mainDelegate messageFieldCaptions] objectAtIndex:0] componentsSeparatedByString:@"|"];
        l= [self newLabelWithPrimaryColor:[mainDelegate navColor] selectedColor:[UIColor whiteColor] fontSize:12.0 bold:YES];
        if (m.sValue0.length>0) 
            l.text=[NSString stringWithFormat:@"%@ %@",[p objectAtIndex:0], m.sValue0];
        else
            l.text=[NSString stringWithFormat:@"%@ None",[p objectAtIndex:0]];

        [l setFrame:CGRectMake(pt.x,pt.y,310,20)];
        [scrollView addSubview:l];
        [l release];
        pt.y+=20;       
    }

    //This is done about 10 more times to add new labels.

}

1 个答案:

答案 0 :(得分:2)

问题出在你的for循环中。当您删除标签时,[[scrollView子视图]计数]会减少,这意味着您将无法访问所有标签,因为循环运行的次数少于标签的次数。

想象一下,你有5个标签:

(At time of comparison)
i | [[scrollView subviews] count] 
=================================
0 | 5
1 | 4 
2 | 3 <-- loop ends here since i+1 >= [[scrollView subviews] count]
3 | 2 

您应该将初始计数保存到变量并在for循环条件中使用它。由于您总是删除索引0,因此您不必担心超出数组范围。