Skip to content →

Three20: Swipe to delete

Need to implement Swipe to delete in your Three20 project? In order to do so, I added the 3 following methods to my datasource (TTListDataSource subclass):

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

- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView beginUpdates];    
	if (editingStyle == UITableViewCellEditingStyleDelete) {	
        // Make sure the row is there to delete
		if([_myModel.messages count] >= indexPath.row){
            // Get the object to delete
			MyObject* myObject = [[_myModel.messages objectAtIndex:indexPath.row] retain];

           	// Remove the object, in my case this makes an API call
            [self removeObjectById: myobject.id];
                            
            // Remove the object from the array
			[_myModel.messages removeObjectAtIndex:indexPath.row];

			// clean up
			TT_RELEASE_SAFELY(myObject);
		}
        // Delete the row from the UITableView
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES];      
	}       
	[tableView endUpdates];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [_myModel.messages count];
}

Note: before adding the numberOfRowsInSection method, I was getting NSInternalInconsistencyException errors.

Published in Apple Code iOS