Andy
Andy

Reputation: 2603

UITableView - Controlling or preventing the delete for a specific row in a section

I am trying to prevent the delete for every last row in every section of my UITableView control. I wrote the code which is working so far.

Is there a way to prevent the delete button from appearing for a specific row in a specific section when in edit mode of UITableView?

Here is the code :

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

    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;

    // If table view is asking to commit a delete command...
    if ( editingStyle == UITableViewCellEditingStyleDelete) {
        // Prevent deleting the last row
        int length = [[[MyItemStore sharedStore] getItemsForGivenSection:section] count];

        // PREVENT LAST ROW FROM DELETING
        if ( row == length) {
            return;
        }

        NSArray *items = [[MyItemStore sharedStore] getItemsForGivenSection:section];
        MyItem *item = items[row];
        [[MyItemStore sharedStore] removeItemFromSection:item fromSection:section];

         //Also remove that row from Table view with animation
        [tableView deleteRowsAtIndexPaths: @[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

Upvotes: 0

Views: 82

Answers (3)

rebello95
rebello95

Reputation: 8576

You could use something like this:

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

    //Return FALSE for the last row
    if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1)
        return FALSE;
    }

    //Return TRUE for all other rows
    return TRUE;
}

Upvotes: 2

ppalancica
ppalancica

Reputation: 4277

You can use this code in the Table View Controller:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView 
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1)
        return UITableViewCellEditingStyleNone;
    }

    return UITableViewCellEditingStyleDelete;
}

Upvotes: 0

Adrian Schönig
Adrian Schönig

Reputation: 1786

You can do this but tableView:commitEditingStyle:forRowAtIndexPath is too late as this gets called when the user already triggered the deletion. You can either return UITableViewCellEditingStyleNone from tableView:editingStyleForRowAtIndexPath: or set the editingStyle property of the UITableViewCell. Sounds like you want to go with the former and return none if it's the last row in each section.

Upvotes: 0

Related Questions