Count the number of selected rows in uitableview

advertisements

What I actually want to do is to count the number of rows selected after selecting and deselecting the row. I get the total count but when I deselect the row I want to get count as how many other rows are still selected. My code is as follows

//countId = 0;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryNone)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        countId = countId + 1;
    }

    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

And then I have to pass the value of countId to another view and display it in a button. I know it is something small but I am not able to do it. Any help would be appreciated.


You can ask the table view for it's currently selected indexes, so if you only need to now how many, you can do:

[self.tableView indexPathsForSelectedRows].count

EDIT:

To keep following the cells with UITableViewCellAccessoryCheckmark you can decrement countId like so:

if (cell.accessoryType == UITableViewCellAccessoryNone)
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    countId = countId + 1;
}

else
{
    cell.accessoryType = UITableViewCellAccessoryNone;
    countId = countId - 1;
}