UIScrollView - 添加/删除标签

问题描述:

我想添加/删除UILabels到ScrollView。添加发生得很好,但我似乎无法在添加新标签之前删除标签。任何人都可以看到这种情况?UIScrollView - 添加/删除标签

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

} 
+0

关于这个非常奇怪的是,关于标签的1/2得到去除,而别人不......如此怪异.... – Dutchie432 2009-05-29 16:23:31

问题出在您的for循环中。当你删除标签时,[[scrollView subviews] count]减少,这意味着你不会得到所有的标签,因为循环运行次数少于标签。

试想一下,你有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 

您应在初步计数保存到一个变量和使用,在您的循环条件。由于您总是删除索引0,因此您不必担心超出数组范围。

+0

哇。我一定有一个漫长的一周。这听起来很明显:) – Dutchie432 2009-05-29 16:30:55