JSA986
JSA986

Reputation: 5936

Prevent first row being deleted in table view

I want to stop all the rows being deleted from my table view by user so at least one row is always present.

Im still geting to grips with programming and objective c.

Heres what I tried:

  if (indexPath.section != 0 | editingStyle == UITableViewCellEditingStyleDelete) {
  [self.managedObjectContext deleteObject:[self.circuits objectAtIndex:indexPath.row]];
  [self.appDelegate saveContext];
  [self.circuits removeObjectAtIndex:indexPath.row];
  [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]             withRowAnimation:UITableViewRowAnimationFade];

then

if (indexPath.section > 1 | editingStyle == UITableViewCellEditingStyleDelete) {
    [self.managedObjectContext deleteObject:[self.circuits objectAtIndex:indexPath.row]];
    [self.appDelegate saveContext];
    [self.circuits removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]             withRowAnimation:UITableViewRowAnimationFade];

That had no effect in that I can still delete the first row. So then I tried

- (BOOL)tableView:(UITableView *)commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) 
    return NO;

return YES;
}

Still cant prevent the first row from being deleted

Upvotes: 1

Views: 133

Answers (3)

Rohit Pathak
Rohit Pathak

Reputation: 359

Try this code :-

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    {
    if(indexPath.row==0)
    return NO;
    else
    return YES;

    }

It will surely help you

Upvotes: 0

Joe
Joe

Reputation: 57179

You need to implement the UITableViewDataSource method tableView:canEditRowAtIndexPath: and return NO for the indexPath.row 0.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.row > 0;
}

Upvotes: 4

Stavash
Stavash

Reputation: 14304

Try moving your code into - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

Upvotes: 2

Related Questions