I am trying to add/remove UILabels to a ScrollView. The adding takes place just fine, but I can not seem to get the labels removed, before adding new ones. Can anyone shed some light on this situation?
-(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.
}
The issue is in your for loop. As you remove labels, [[scrollView subviews] count] decreases, which means you won’t get to all your labels since the loop runs less times than there are labels.
Imagine you had 5 labels:
You should save the initial count to a variable and use that in your for loop condition. Since you are always removing index 0, you don’t have to worry about going out of bounds of the array.