2010-08-16 18 views
5

Tengo un UITableView y básicamente estoy haciendo algunos ajustes en la aplicación, y si la primera sección es UISegmentedControl se cambia al índice 1, entonces quiero mostrar una nueva sección, pero si el índice 1 se estableció previamente y el usuario selecciona el índice 0 entonces necesidad de quitar la sección 2.UITableView agregar/eliminar secciones mientras no está en modo de edición?

para ello he tenido este código configurado para disparar en el UISegmentedControl's valueChanged event

if (segmentControl.selectedSegmentIndex == 0) 
{ 
    self.settings.useMetric = YES; 
    if ([sections containsObject:FT_AND_IN] && [sections containsObject:FRACTION_PRECISION]) { 

     NSArray *indexSections = [NSArray arrayWithObjects: 
      [NSIndexPath indexPathForRow:0 inSection: 
       [sections indexOfObject:FT_AND_IN]], 
      [NSIndexPath indexPathForRow:0 inSection: 
       [sections indexOfObject:FRACTION_PRECISION]], nil]; 
     [sections removeObject:FT_AND_IN]; 
     [sections removeObject:FRACTION_PRECISION]; 
     [self.tableView deleteRowsAtIndexPaths:indexSections 
      withRowAnimation:UITableViewRowAnimationRight]; 
    } 
} 
else { 
    self.settings.useMetric = NO; 
    [sections insertObject:FT_AND_IN atIndex:1]; 
    [sections insertObject:FRACTION_PRECISION atIndex:2]; 
    NSArray *indexSections = [NSArray arrayWithObjects: 
     [NSIndexPath indexPathForRow:0 inSection: 
      [sections indexOfObject:FT_AND_IN]], 
     [NSIndexPath indexPathForRow:0 inSection: 
      [sections indexOfObject:FRACTION_PRECISION]], nil]; 
    [self.tableView insertRowsAtIndexPaths:indexSections 
     withRowAnimation:UITableViewRowAnimationRight]; 
} 

Cuando la llamada NSMutableArraysections es la lista de todas las secciones. Cada sección solo tiene 1 fila por lo que no se necesitan sub-arrays.

Sin embargo cuando se evalúa la parte else me sale este error:

*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], 
    /SourceCache/UIKit_Sim/UIKit-1261.5/UITableView.m:904 
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
    reason: 'Invalid update: invalid number of sections. The number of sections 
    contained in the table view after the update (6) must be equal to the number of 
    sections contained in the table view before the update (4), plus or minus the 
    number of sections inserted or deleted (0 inserted, 0 deleted).' 

He verificado que tenía 4 secciones con anterioridad a la otra, se añadió correctamente las dos secciones de la matriz sections, lo dije el indexPaths apropiado para las secciones agregadas. ¿Por qué esto no funciona?

He intentado reemplazar la línea [self.tableView insertRows/deleteRows...] con [self.tableView reloadData]; y luego funciona bien, pero quiero animar a agregar/eliminar esas secciones.

actualización me trataron esta sugerencia y obras añadiendo Pero me estoy rompiendo en la eliminación de

[self.tableView beginUpdates]; 
if (segmentControl.selectedSegmentIndex == 0) 
{ 
     self.settings.useMetric = YES; 
    if ([sections containsObject:FT_AND_IN] && 
      [sections containsObject:FRACTION_PRECISION]) 
     { 

     [self.tableView deleteSections:[NSIndexSet indexSetWithIndex: 
       [sections indexOfObject:FT_AND_IN]] 
       withRowAnimation:UITableViewRowAnimationRight]; 
     [self.tableView deleteSections:[NSIndexSet indexSetWithIndex: 
       [sections indexOfObject:FRACTION_PRECISION]] 
       withRowAnimation:UITableViewRowAnimationRight]; 
    } 
} 
else 
    { 
     self.settings.useMetric = NO; 
    [sections insertObject:FT_AND_IN atIndex:1]; 
     [sections insertObject:FRACTION_PRECISION atIndex:2]; 
     NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1]; 
    NSIndexSet *indexSet2 = [NSIndexSet indexSetWithIndex:2]; 
    [self.tableView insertSections:indexSet 
      withRowAnimation:UITableViewRowAnimationRight]; 
    [self.tableView insertSections:indexSet2 
      withRowAnimation:UITableViewRowAnimationRight]; 
} 
[self.tableView endUpdates]; 

consigo este error.

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** - 
    [NSIndexSet initWithIndexesInRange:]: Range {2147483647, 1} exceeds 
    maximum index value of NSNotFound - 1' 

Los FT_AND_IN y FRACTION_PRECISION objetos sólo se añaden/retirado del almacén de datos en el código, y no son más que const NSString objetos.

+0

Estar triste ver a personas con puntuación más alta no formatea el código – vodkhang

+0

Se supone que funciona bien. No puedo ver ningún problema ¿Puedes verificar dos veces la matriz indexSections? – vodkhang

Respuesta

4

Es muy difícil leer allí su código sin formato.

Quiere ver -[UITableView insertSections:withRowAnimation:] y -[UITableView deleteSections:withRowAnimation], creo.

Probar:

if (segmentControl.selectedSegmentIndex == 0) 
{ 
    self.settings.useMetric = YES; 
    if ([sections containsObject:FT_AND_IN] && [sections containsObject:FRACTION_PRECISION]) { 

     NSMutableIndexSet *indexSections = [NSMutableIndexSet indexSetWithIndex:[sections indexOfObject:FT_AND_IN]]; 
     [indexSections addIndex:[sections indexOfObject:FRACTION_PRECISION]]; 

     [sections removeObject:FT_AND_IN]; 
     [sections removeObject:FRACTION_PRECISION]; 

     [self.tableView deleteSections:indexSections 
      withRowAnimation:UITableViewRowAnimationRight]; 
    } 
} 
else { 
    self.settings.useMetric = NO; 
    [sections insertObject:FT_AND_IN atIndex:1]; 
    [sections insertObject:FRACTION_PRECISION atIndex:2]; 

    NSMutableIndexSet *indexSections = [NSMutableIndexSet indexSetWithIndex:[sections indexOfObject:FT_AND_IN]]; 
    [indexSections addIndex:[sections indexOfObject:FRACTION_PRECISION]]; 

    [self.tableView insertSections:indexSections 
      withRowAnimation:UITableViewRowAnimationRight]; 
} 
+0

Todavía no estoy seguro de por qué la versión editada de myne no funcionó, pero la tuya sí. El único problema con el tuyo es que la línea '[self.tableView addSections ...]' debe ser 'insertSections'. ¡Gracias! – jamone

Cuestiones relacionadas