2008-12-01 10 views
6

Tengo un poco de dolor al insertar y eliminar UITableViewCells desde el mismo UITableView!Insertar y eliminar UITableViewCell al mismo tiempo no funciona

normalmente no suelo publicar código, pero pensé que esta era la mejor manera de mostrar donde estoy teniendo el problema:


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 5; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    if (iSelectedSection == section) return 5; 
    return 1; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    //NSLog(@"drawing row:%d section:%d", [indexPath row], [indexPath section]); 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    if (iSelectedSection == [indexPath section]) { 
     cell.textColor = [UIColor redColor]; 
    } else { 
     cell.textColor = [UIColor blackColor]; 
    } 


    cell.text = [NSString stringWithFormat:@"Section: %d Row: %d", [indexPath section], [indexPath row]]; 

    // Set up the cell 
    return cell; 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    // Navigation logic -- create and push a new view controller 

    if ([indexPath row] == 0) { 

     NSMutableArray *rowsToRemove = [NSMutableArray array]; 
     NSMutableArray *rowsToAdd = [NSMutableArray array]; 

     for(int i=0; i<5; i++) { 

      //NSLog(@"Adding row:%d section:%d ", i, [indexPath section]); 
      //NSLog(@"Removing row:%d section:%d ", i, iSelectedSection); 

      [rowsToAdd addObject:[NSIndexPath indexPathForRow:i inSection:[indexPath section]]]; 
      [rowsToRemove addObject:[NSIndexPath indexPathForRow:i inSection:iSelectedSection]]; 

     } 

     iSelectedSection = [indexPath section]; 

     [tableView beginUpdates]; 
     [tableView deleteRowsAtIndexPaths:rowsToRemove withRowAnimation:YES]; 
     [tableView insertRowsAtIndexPaths:rowsToAdd withRowAnimation:YES]; 
     [tableView endUpdates]; 

    } 
} 

Este código crea 5 secciones, la Primero (indexado de 0) con 5 filas. Cuando selecciona una sección, elimina las filas de la sección que había seleccionado previamente y agrega filas a la sección que acaba de seleccionar.

Pictorally, cuando cargo la aplicación, que tiene algo como esto:

http://www.freeimagehosting.net/uploads/1b9f2d57e7.png http://www.freeimagehosting.net/uploads/1b9f2d57e7.png

imagen aquí: http://www.freeimagehosting.net/uploads/1b9f2d57e7.png

Después de seleccionar una fila de tabla 0 de la sección 2, que elimine la filas de la sección 1 (que es seleccionado por defecto) y añadir las filas de la sección 2. Pero me sale esto:

http://www.freeimagehosting.net/uploads/6d5d904e84.png http://www.freeimagehosting.net/uploads/6d5d904e84.png

Imagen aquí: http://www.freeimagehosting.net/uploads/6d5d904e84.png

... que no es lo que espero que suceda! Parece que la primera fila de la sección 2 permanece de alguna manera, aunque definitivamente se elimina.

Si acabo de hacer un [tableView reloadData], todo aparece como normal ... pero obviamente guardo las bonitas animaciones.

¡Realmente agradecería que alguien pudiera hacer brillar la luz aquí! ¡Me está volviendo un poco loco!

Gracias de nuevo, Nick.

Respuesta

0

FYI: Parece que este error se ha solucionado por completo con la actualización del iPhone 2.2. Gracias Apple! Nick.

0

En el código que publicó, su índice de ciclo va de 0 a 4, lo que sugiere que eliminaría todas de las filas en la sección 1, y luego agregaría cinco nuevas filas a la sección 2. Como cada sección ya tiene una fila 0, esto agregaría una segunda instancia de de la sección 2, fila 0 a la tabla.

Yo sugeriría tener su bucle de ejecución de 1 a 4:

for (int i=1; i<5; i++) 
{ 
    // ... 
}
+0

Hey eJames, gracias por su comentario - un punto muy válido !! Pensé por un momento que podría resolver mi problema, pero todavía tengo el mismo problema. Creo que en realidad podría haber un iPhone, pero cuando intentas eliminar elementos de una sección y agregarlos a otra sección al mismo tiempo ... –

1

Me parece recordar que numberOfRowsInSection: se llamará cuando se llama DeleteRows o insertRow, es necesario tener mucho cuidado de que el numberOfRowsInSection realidad Williams coincide con tus cambios. En este caso, puede intentar mover la sección iSelectedSection = [indexPath]; línea a después del final Actualizaciones.

1

No recuerdo dónde lo leí, pero creo que no debe realizar actualizaciones de fila de tabla (inserciones y eliminaciones) desde el interior de una de las funciones delegadas de la vista de tabla. Creo que una mejor alternativa sería hacer un performSelectorOnMainThread pasando la información necesaria para realizar las actualizaciones como un objeto.Algo como:

- (void)tableView:(UITableView *)tableView 
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    // .... 
    [self performSelectorOnMainThread: @selector(insertRows:) 
          withObject: someObjectOrNil]; // double check args 
} 

- (void) insertRows: (NSObject*)someObjectOrNil { 
    [tableView beginUpdates]; 
    // update logic 
    [tableView endUpdates]; 

    // don't call reloadData here, but ensure that data returned from the 
    // table view delegate functions are in sync 
} 
6

Luchado para hacer que esto funcione. Aquí está mi código para agregar una fila a mi tableView:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
[tableView beginUpdates]; 
[dataSource insertObject:[artistField text] atIndex:0]; 
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop]; 
[tableView endUpdates]; 
Cuestiones relacionadas