user1028028
user1028028

Reputation: 6433

TableView not selecting new row on deletion

When I delete a row in my tableView I want the row above it to be selected. This doesn't happen...

Here is the code:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        if (indexPath.section == 0) {
            Formula *toDelete = (Formula *)[self.userFRMList objectAtIndex:indexPath.row];
            NSManagedObjectContext *context = (NSManagedObjectContext *)[(PSAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
            NSError *error = nil;
            [context deleteObject:toDelete];
            [context save:&error];
            [self updateDataSource];
            [tableView beginUpdates];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            if ([self.userFRMList count] != 0) {

                if (indexPath.row == 0) {
                    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
                    self.crtFormula = [self.userFRMList objectAtIndex:0];
                    [self.delegate theFormulaIs:self.crtFormula];

                } else {
                    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row - 1  inSection:indexPath.section] animated:YES scrollPosition:UITableViewScrollPositionNone];
                    self.crtFormula = [self.userFRMList objectAtIndex:indexPath.row - 1];
                    [self.delegate theFormulaIs:self.crtFormula];

                }
            }else {
                self.crtFormula = nil;
                [self.delegate showBlank];
            }
            [tableView endUpdates];
        }

    }   

}

Upvotes: 0

Views: 209

Answers (2)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

// For example I have set deletedRowIndex to 10, and next Line will select Row Number 9 in tableview
int deletedRowIndex = 10;
[tblViewList selectRowAtIndexPath:[NSIndexPath indexPathWithIndex:deletedRowIndex-1] animated:YES scrollPosition:UITableViewScrollPositionMiddle];

Upvotes: 0

matt
matt

Reputation: 535247

At the very least, the selection part needs to be outside the updates block! Put it after your endUpdates call.

If that doesn't work, go even further: Try doing the selection part using delayed performance (e.g. dispatch_after). Right now you're trying to perform the selection while we're still in the middle of responding to commitEditingStyle - we haven't even deleted the row yet. Delayed performance lets the interface settle down after the deletion.

You will need to use index numbering corresponding to the situation after the deletion.

Upvotes: 1

Related Questions