2011-06-03 12 views
6

En mi aplicación, necesito eliminar varias filas en una tabla, editar la tabla y obtener una casilla de verificación al lado de la tabla. Cuando se selecciona, las celdas de la tabla se eliminan. Es como la aplicación de mensajes de iPhone. ¿Cómo puedo hacer esto? Por favor, ayúdenme.Edite y elimine varias filas en UITableView simultáneamente

+0

posible duplicado de [seleccionar múltiples filas de uitableview y eliminar] (http://stackoverflow.com/questi ons/4954393/select-multiple-rows-from-uitableview-and-delete) –

+0

Otros duplicados: [1] (http://stackoverflow.com/questions/6222661/how-to-delete-multiple-rows-in- tabla-vista) [2] (http://stackoverflow.com/questions/2727302/) [3] (http://stackoverflow.com/questions/2949488/) [4] (http://stackoverflow.com/ preguntas/5973756 /) –

Respuesta

18

Si entiendo su pregunta correctamente, esencialmente desea marcaUITableViewCell s de alguna manera (una marca de verificación); luego, cuando el usuario toca un botón maestro "Eliminar", todos los marcados comoUITableViewCell s se eliminan del UITableView junto con sus objetos fuente de datos correspondientes.

Para poner en práctica la parte marca de verificación, es posible considerar alternar entre UITableViewCellAccessoryCheckmark y UITableViewCellAccessoryNone para accessory propiedad del UITableViewCell 's. Manejar toques en el siguiente método UITableViewController delegado:

- (void)tableView:(UITableView *)tableView 
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *c = [tableView cellForRowAtIndexPath:indexPath]; 
    if (c.accessoryType == UITableViewCellAccessoryCheckmark) { 
     [c setAccessoryType:UITableViewCellAccessoryNone]; 
    } 
    //else do the opposite 

} 

También puede ser que look at this post respecto encargo UITableViewCell s si usted está queriendo una marca de verificación más compleja .

Puede configurar un maestro "Borrar" botón de dos maneras:

En cualquiera de los casos, con el tiempo un método debe ser llamado cuando el maestro "Borrar" se presiona el botón. Ese método solo necesita recorrer el UITableViewCells en el UITableView y determinar cuáles están marcados. Si está marcado, elimínelos.Suponiendo una sola sección:

NSMutableArray *cellIndicesToBeDeleted = [[NSMutableArray alloc] init]; 
for (int i = 0; i < [tableView numberOfRowsInSection:0]; i++) { 
    NSIndexPath *p = [NSIndexPath indexPathWithIndex:i]; 
    if ([[tableView cellForRowAtIndexPath:p] accessoryType] == 
     UITableViewCellAccessoryCheckmark) { 
     [cellIndicesToBeDeleted addObject:p]; 
     /* 
      perform deletion on data source 
      object here with i as the index 
      for whatever array-like structure 
      you're using to house the data 
      objects behind your UITableViewCells 
     */ 
    } 
} 
[tableView deleteRowsAtIndexPaths:cellIndicesToBeDeleted 
       withRowAnimation:UITableViewRowAnimationLeft]; 
[cellIndicesToBeDeleted release]; 

asumiendo por "editar" que significa "borrar un solo UITableViewCell" o "mover un solo UITableViewCell," se puede poner en práctica los métodos siguientes en el UITableViewController:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // This line gives you the Edit button that automatically comes with a UITableView 
    // You'll need to make sure you are showing the UINavigationBar for this button to appear 
    // Of course, you could use other buttons/@selectors to handle this too 
    self.navigationItem.rightBarButtonItem = self.editButtonItem; 

} 

// Override to support conditional editing of the table view. 
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { 
    return YES; 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 

    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     //perform similar delete action as above but for one cell 
    } 
} 

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { 
    //handle movement of UITableViewCells here 
    //UITableView cells don't just swap places; one moves directly to an index, others shift by 1 position. 
} 
+1

Eso es lo que llamo "lectura mental". Gracias. – Flar

+0

Magnífica respuesta. – aejhyun

1

que quieren estar en busca de deleteRowsAtIndexPath, con todo su código apretado entre [yourTable beginUpdates] & [yourTable endUpdates];

2

Usted puede poner 1 UIButton le llaman "EDIT" y el alambre hasta que IBAction. En IBAction escriba para que pueda hacer según sus necesidades.

-(IBAction)editTableForDeletingRow 
{ 
     [yourUITableViewNmae setEditing:editing animated:YES]; 
} 

Esto agregará botones redondos de color rojo en la esquina izquierda y puede hacer clic en ese botón Borrar aparecerá clic en eso y se borrará fila.

Puede implementar el método delegado de UITableView de la siguiente manera.

-(UITableViewCellEditingStyle)tableView: (UITableView *)tableView editingStyleForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
     //Do needed stuff here. Like removing values from stored NSMutableArray or UITableView datasource 
} 

Espero que ayude.

1

encontré un código muy agradable aquí Utilice este código para implementar la funcionalidad determinada Tutorials Link

Cuestiones relacionadas