Pregunta

Estoy tratando de añadir / eliminar UILabels a un ScrollView. La adición se lleva a cabo muy bien, pero me parece que no puede conseguir las etiquetas retirados, antes de añadir otros nuevos. ¿Alguien puede arrojar algo de luz sobre esta situación?

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

}
¿Fue útil?

Solución

El problema está en su bucle. Como quitar las etiquetas, [[ScrollView subvistas] count] disminuye, lo que significa que no se llega a todas las etiquetas ya que el bucle se ejecuta menos veces que los que hay etiquetas.

Imagine que tiene 5 etiquetas:

(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 

Debe guardar el conteo inicial a una variable y el uso que en su condición de bucle. Ya que siempre está quitando el índice 0, usted no tiene que preocuparse de ir fuera de los límites de la matriz.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top