JTApps JTApps - 1 year ago 165
iOS Question

Swipe To Delete TableView Row

I have my array:

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

I've tried everything I can find, but there's always errors. I want to be able to swipe so that the delete button appears, and then press the delete button and have that row removed.

Full code (everything relating to the table):

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {

IBOutlet UITableView *tableView;
NSMutableArray *colorNames;

@property (strong, nonatomic) NSArray *colorNames;



#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]

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

return cell;


Answer Source

You have to implement the necessary UITableViewDelegate and UITableViewDataSource methods.

First, add this:

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


- (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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download