2012-01-24 12 views
72

Ho un UIViewController che implementa i delegati TableViews e i datasource protocolli. Ora voglio aggiungere il gesto "striscia per eliminare" alle celle.Come abilitare lo scorrimento per eliminare la cella in un TableView?

Come dovrei farlo.

Ho dato un'implementazione vuota del metodo commitEditingStyle e ho anche impostato la proprietà Modifica su SÌ.

Ancora la funzione di scorrimento non viene.

Ora Devo aggiungere separatamente UISwipeGesture a ciascuna cella?

O mi manca qualcosa?

+0

consultare il link, si può aiutare, http://stackoverflow.com/questions/3309484/uitableviewcell- show-delete-button-on-swipe – Sharme

+2

Ho sovrascritto commitEditingStyle e ho impostato Modifica su YES e anche NOW ho sovrascritto CanEditRowAtIndexPath. I normali comandi di modifica vengono visualizzati in cui appare il clic sul pulsante di cancellazione. Ma non per lo swiping! È perché la mia classe è una sottoclasse di UIViewController e implementa solo i metodi delegato e origine dati ma non di UITableViewController che potrebbe fare qualcosa per abilitare un gesto di scorrimento. –

+0

Ho appena impostato un UITableView come IBOutlet in un UIViewController ieri, e seguendo esattamente il post che ho mostrato, ho fatto scorrere il dito per cancellare. Quindi posso dire che non è necessario abilitare i gesti di scorrimento, anche se se davvero non riesci a farlo funzionare in un altro modo, potresti dover ricorrere a quello. – gurooj

risposta

51

Non è necessario impostare editing:YES se è necessario mostrare il pulsante Elimina sullo scorrimento della cella. Devi implementare tableView:canEditRowAtIndexPath: e restituire SÌ da lì per le righe che devi modificare/eliminare. Questo non è necessario quando il dataSource del tuo tableView è una sottoclasse di UITableViewContoller - questo metodo, se non sovrascritto, restituisce SÌ per impostazione predefinita. In tutti gli altri casi è necessario implementarlo.

EDIT: insieme abbiamo trovato il problema - tableView:editingStyleForRowAtIndexPath: restituito UITableViewCellEditingStyleNone se la tabella non era in modalità di modifica.

+1

Fatto tutto ma ancora non funziona! –

+0

Hai rimosso '[tableView setEditing: YES];'? –

+0

Se lo rimuovo, il pulsante di eliminazione di base non viene affatto! –

5

Prova ad aggiungere il seguente alla classe:

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

non funziona per me :( È perché la mia classe è una sottoclasse di UIViewController e devo fare qualcosa in più che UITabelViewController fa? –

+1

@AmoghTalpallikar, Come hai risolto il tuo problema? Ho anche lo stesso problema. Anche la mia classe è una sottoclasse di UIViewController e tutte le celle del mio tableView sono sottoclasse di UITableViewCell. – Shamsiddin

3

Conclusione di Kyr Dunenkoff di chat è

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

} 

non dovrebbe essere definito se è necessario il pulsante a comparire su colpo eliminare.

59

Come Dan ha commentato in precedenza, è necessario implementare le seguenti vista tabella metodi delegato:

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

Nota: Ho provato questo 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."); 
} 
+2

funzionerà con ios 8 – iOSDeveloper

+0

in realtà non funziona su ios8 – Reaper

+3

Ho appena provato questo in iOS 8.1.2 su un iPhone 6 e funziona. Ho solo bisogno di implementare il '- (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editStyle forRowAtIndexPath: (NSIndexPath *) indexPath' come metodo dovrebbe essere SÌ da default – neonhomer

25
// 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 
    } 
} 
+5

Degno di nota/commento per neofiti come me: t la riga deve ancora essere eliminata, così come l'origine dati (ad es. array) deve essere ridotto. – BananaAcid

-2

È possibile visualizzare tutti i metodi necessari creando una classe UITableViewController (temporanea) in XCode 5 e quindi copiare il metodo che si desidera utilizzare. I metodi di cui hai bisogno verranno commentati con linee pre-riempite che desideri.

+1

Bene, questa risposta è per le altre persone che stanno cercando la risposta, di sicuro. :) –

0

Questo era un problema anche per me ... Potevo solo strisciare per eliminare a lavorare una volta ogni 10 tentativi. Si scopre che il gesture sul televisore era bloccato da un altro gesto nel controller della vista genitore. Il televisore è stato nidificato in un MMDrawerController (layout cassetto scorrevole).

La semplice configurazione del rilevatore di gesti nel controller del cassetto per non rispondere a gesti ravvicinati nei cassetti affiancati ha consentito di far scorrere il dito sullo schermo per funzionare sulla TV.

Si potrebbe anche provare a fare qualcosa di simile con il gesture delegate:

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

So che questo è vecchio, ma sto avendo lo stesso esatto problema con MMDrawerController .. Potresti approfondire "la configurazione del riconoscitore di gesti nel controller del cassetto per non rispondere a gesti stretti nei cassetti laterali consentiti di scorrere per eliminare a lavoro nella mia TV ". Come si fa a farlo? – Mark

-1
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]; 
    } 
} 
0

Questa è la rapida versione

// 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 
    }  
} 
13

Si prega di provare questo codice 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] 
} 
0

Se si si utilizza un NSFetchedResultsControllerDelegate per popolare la visualizzazione della tabella, questo ha funzionato per me:

  • assicurarsi tableView:canEditRowAtIndexPath restituisce true sempre
  • Nella tua tableView:commitEditingStyle:forRowAtIndexPath implementazione, non eliminare la riga direttamente dalla vista tabella. Invece, eliminarlo utilizzando il contesto di oggetto gestito, ad es .:

    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)") 
        } 
    } 
    
0

Nella mia esperienza, sembra che è necessario disporre di editing su UITableView set per NO per strisciare a lavorare.

self.tableView.editing = NO;

0

Dopo iOS 8.0, è possibile personalizzato azione

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath 
Problemi correlati