Domanda

Ho un UIViewController che implementa il delegato e la dati dati di tabelle protocolli. Ora voglio aggiungere un gesto "Swipe per eliminare" alle cellule.

Come dovrei procedere.

Ho dato un'implementazione vuota di commitEditingStyle metodo e anche impostare la proprietà di modifica su Sì.

Tuttavia la funzione di scorrimento non sta arrivando.

Ora devo aggiungere separatamente UISwipeGesture a ogni cella?

Oppure mi sfugge qualcosa ?

È stato utile?

Soluzione

Non devi impostare editing:YES Se hai bisogno di mostrare il pulsante Elimina su cell swipe. Devi implementare tableView:canEditRowAtIndexPath: e restituisci sì da lì per le righe è necessario modificare/eliminare. Ciò non è necessario quando DataSource della tua tabella è una sottoclasse di UableViewContoller: questo metodo, se non sovrascritto, restituisce sì per impostazione predefinita. In tutti gli altri casi devi implementarlo.

MODIFICARE: Insieme abbiamo trovato il problema - tableView:editingStyleForRowAtIndexPath: restituito UITableViewCellEditingStyleNone Se la tabella non era in modalità di modifica.

Altri suggerimenti

Come Dan ha commentato sopra, è necessario implementare i seguenti metodi delegati della visualizzazione della tabella:

  1. tableView:canEditRowAtIndexPath:
  2. tableView:commitEditingStyle:forRowAtIndexPath:

Nota: l'ho provato in iOS 6 e iOS 7.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return YES - we will be able to delete all rows
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Perform the real delete action here. Note: you may need to check editing style
    //   if you do not perform delete only.
    NSLog(@"Deleted row.");
}
// 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;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

Prova questo codice in Swift,

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
   // let the controller to know that able to edit tableView's row 
   return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)  {
   // if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?  {
   // add the action button you want to show when swiping on tableView's cell , in this case add the delete button.
   let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in

   // Your delete code here.....
   .........
   .........
   })

   // You can set its properties like normal button
   deleteAction.backgroundColor = UIColor.redColor()

   return [deleteAction]
}

Prova ad aggiungere quanto segue alla tua classe:

// Override to support conditional editing of the table view.
- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return(YES);
}

Conclusione di Kyr Dunenkoff La chat è

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

}

Non dovrebbe essere definito se è necessario che il pulsante Elimina per apparire su SWIPE.

Se stai usando un NSFetchedResultsControllerDelegate Per popolare la vista del tavolo, questo ha funzionato per me:

  • Assicurarsi tableView:canEditRowAtIndexPath Restituisce sempre vero
  • Nel tuo tableView:commitEditingStyle:forRowAtIndexPath Implementazione, non eliminare la riga direttamente dalla vista della tabella. Invece, eliminalo usando il contesto dell'oggetto gestito, ad esempio:

    if editingStyle == UITableViewCellEditingStyle.Delete {
        let word = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Word
        self.managedObjectContext.deleteObject(word)
        self.saveManagedObjectContext()
    }
    
    func saveManagedObjectContext() {
        do {
            try self.managedObjectContext.save()
        } catch {
            let saveError = error as NSError
            print("\(saveError), \(saveError.userInfo)")
        }
    }
    

Questa è la versione rapida

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
}

// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}

Questo è stato un problema anche per me ... Potevo solo scorrere per eliminare per lavorare una volta ogni 10 tentativi. Si scopre gesture Sulla TV veniva bloccato da un altro gesto nel controller di vista genitore. La TV è stata nidificata in un MMDrawerController (Swipe Able Drewer Layout).

La semplice configurazione del riconoscimento dei gesti nel controller del cassetto per non rispondere ai gesti chiusi nei cassetti fiancheggianti ha permesso di scorrere per eliminare per lavorare nella mia TV.

Potresti anche provare a fare qualcosa del genere con il gesture delegate:

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

Nella mia esperienza, sembra che tu debba avere editing Su UITableView impostato NO per scorrere al lavoro.

self.tableView.editing = NO;

Dopo iOS 8.0, puoi personalizzare la tua azione

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
NSMutableArray *post= [NSMutableArray alloc]initWithObject:@"1",@"2",@"3",nil]; 


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView 
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSUInteger row = [indexPath row];
    NSUInteger count = [posts count];

    if (row < count) {
        return UITableViewCellEditingStyleDelete;
    } else {
        return UITableViewCellEditingStyleNone;
    }
}

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

    NSUInteger row = [indexPath row];
    NSUInteger count = [posts count];

    if (row < count) {

        [posts removeObjectAtIndex:row];
    }
}

Puoi vedere tutti i metodi necessari creando una classe UableViewController (temporanea) in Xcode 5 e quindi copiare quale metodo si desidera utilizzare. Quei metodi di cui hai bisogno verranno commentati con le linee pre-riempite che desideri.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top