Search code examples
iosobjective-cuitableviewselectionnsindexpath

How to select only two rows in tableview in iOS?


I am trying to allow just two rows to be selected at a time in a table view, but it seems that I can't get a good result!

The idea is that you select one row and this sends an object to core data, then when you select a second row that sends a different thing to core data. But if you select more than two rows, it displays an alert view that says you can only select two rows.

I have tried this:

    NSArray *indexPathArray = [[NSArray alloc]init];
indexPathArray = [self.mainTableView indexPathsForSelectedRows];

if ( indexPathArray.count == 1) {
    NSLog(@"%@",@"we have 1 cell selected");
}
if ( indexPathArray.count == 2) {
    NSLog(@"%@",@"We have 2 cells selected!");
}
if (indexPathArray.count > 2) {
    NSLog(@"%@",@"ERROR ERROR!!!");
}

and I have tried many other google and stack overflow suggestions but didn't get to an end!

So how can I achieve this?

This is the method in which I have the code:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath(NSIndexPath*)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];

[self setSelection:indexPath];
_profile = [self.fetchedResultsController objectAtIndexPath:indexPath];

NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
    rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
NSLog(@"%ld",(long)rowNumber);

NSArray *indexPathArray = [[NSArray alloc]init];
indexPathArray = [self.mainTableView indexPathsForSelectedRows];

if ( indexPathArray.count == 1) {
    NSLog(@"%@",@"we have 1 cell selected");
}
if ( indexPathArray.count == 2) {
    NSLog(@"%@",@"We have 2 cells selected!");
}
if (indexPathArray.count > 2) {
    NSLog(@"%@",@"ERROR ERROR!!!");
}
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];      }

Solution

  • Comment/Delete out the following lines in your code in method
    - (void)tableView:(UITableView )tableView didSelectRowAtIndexPath(NSIndexPath)indexPath

    [tableView deselectRowAtIndexPath:indexPath animated:YES];  
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    

    And check. Your logical part should then work fine.

    Explanation: TableView method indexPathsForSelectedRows will return the number of rows selected. And your are deselecting the selected row using this line of code:

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    Commenting/deleting only this single line of code will give you indexPathArray count as 1, because you still reload the row at the end of your method using:

    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    

    The above piece of code also resets the row to be unselected as you are reloading it. So you need to comment or delete it out too.