2012-02-27 13 views
27

ho la mia matrice:scorri per eliminare TableView Row

self.colorNames = [[NSArray alloc] 
initWithObjects:@"Red", @"Green", 
@"Blue", @"Indigo", @"Violet", nil]; 

Ho provato tutto quello che riesco a trovare, ma c'è sempre errori. Voglio essere in grado di scorrere in modo che venga visualizzato il pulsante Elimina, quindi premere il pulsante Elimina e rimuovere quella riga.

codice completa (tutto ciò che riguarda la tabella):

// HEADER FILE 
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { 

    IBOutlet UITableView *tableView; 
    NSMutableArray *colorNames; 

} 
@property (strong, nonatomic) NSArray *colorNames; 


@end 

// IMPLEMENTATION 

#import "ViewController.h" 

@implementation ViewController 

@synthesize colorNames; 

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    self.colorNames = [[NSMutableArray alloc] 
    initWithObjects:@"Red", @"Green", 
    @"Blue", @"Indigo", @"Violet", nil]; 

    [super viewDidLoad]; 
    //[tableView setEditing:YES animated:NO]; 
} 


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

// Customize the number of rows in the table view. 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    int count = [colorNames count]; 
    return count; 
} 

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

} 

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 
    cell = [[UITableViewCell alloc] 
      initWithStyle:UITableViewCellStyleDefault 
      reuseIdentifier:CellIdentifier]; 

} 
    // Configure the cell. 
    cell.textLabel.text = [self.colorNames objectAtIndex: [indexPath row]]; 

return cell; 

} 
+0

che hai postato solo un 'NSArray' qui. Si prega di pubblicare il codice relativo per come si imposta 'UITableView'. – PengOne

+0

È lì. Si prega di offrire qualsiasi input possibile, in quanto apprezzo qualsiasi tipo di aiuto. – JTApps

risposta

121

Bisogna attuare le necessarie UITableViewDelegate e UITableViewDataSource metodi.

In primo luogo, aggiungere questo:

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

Poi:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     //remove the deleted object from your data source. 
     //If your data source is an NSMutableArray, do this 
     [self.dataArray removeObjectAtIndex:indexPath.row]; 
     [tableView reloadData]; // tell table to refresh now 
    } 
} 
+0

Sono arrivato così lontano, tuttavia ho bisogno di sapere cosa mettere effettivamente in questi metodi. Sono arrivato a questo punto una dozzina di volte, ma vengo sempre in una specie di barriera a causa di tutorial antiquati. – JTApps

+0

Questi metodi non sono cambiati molto dalla creazione di iOS. Tutorial obsoleti dovrebbero funzionare bene. – edc1591

+0

Ho aggiornato la mia risposta. – edc1591

4

Implementare il seguente metodo:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return UITableViewCellEditingStyleDelete; 
} 
+0

L'ho già aggiunto. Quello che devo fare è in realtà consentire la cancellazione. – JTApps

+0

Se si desidera solo eliminare, non sembra che sia necessario implementare questo metodo poiché il pulsante "Elimina" è il comportamento predefinito. –

21

Per cominciare, il tuo colorNames dovrebbe essere un NSMutableArray piuttosto che un NSArray. Non è possibile aggiungere o rimuovere oggetti da una matrice regolare (non modificabile); dovresti ricrearlo ogni volta che hai apportato una modifica. Cambiare che renderà più facile. Per l'implementazione di -tableView:commitEditingStyle:forRowAtIndexPath:, sarete quindi in grado di fare qualcosa del genere:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if(editingStyle == UITableViewCellEditingStyleDelete) 
    { 
     [colorNames removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft]; 
    } 
} 
+1

La parte di array mutabile ha aiutato, non so perché non l'ho catturato prima! – JTApps

+2

+1 per [tableView deleteRowsAtIndexPaths] per rendere l'aggiornamento dell'interfaccia utente e l'origine dati –

0

Questo è ciò che ha funzionato per me

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

    if (editingStyle == UITableViewCellEditingStyleDelete){ 
     Comment *comment = [self.commentArray objectAtIndex:indexPath.row]; 
     dispatch_async(kBgQueue, ^{ 
      if([self.thePost deleteCommentForCommentId:comment.commentId]){ 
       if (indexPath.row < self.commentArray.count) { 
        [self.commentArray removeObjectAtIndex:indexPath.row]; 
       } 
       dispatch_async(dispatch_get_main_queue(), ^{ 

        [self.tvComments reloadData]; 
       }); 
      } 
     }); 
    } 
    [self.tvComments reloadData]; 
} 
0

Swift Versione:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == UITableViewCellEditingStyle.Delete { 
     dataArray?.removeAtIndex(indexPath.row) 
     tableview.reloadData() 
    } 
} 
3

Risposta Swift 3 e Swift 4 senza utilizzare reloadData

Preferisco usare deleteRows invece di utilizzare reloadData.

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
    // Enables editing only for the selected table view, if you have multiple table views 
    return tableView == yourTableView 
} 

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     // Deleting new item in the table 
     yourTableView.beginUpdates() 
     yourDataArray.remove(at: indexPath.row) 
     yourTableView.deleteRows(at: [indexPath], with: .automatic) 
     yourTableView.endUpdates() 
    } 
} 
+1

deleteRows gestisce già gli aggiornamenti di tableView. Puoi omettere begin/endUpdates. – Rob

0

Swift 4 Versione:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { 
    let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in 
     // delete item at indexPath 

    } 
    return [delete] 
} 
Problemi correlati