Thursday, June 6, 2013

UITableView allowsMultipleSelection example in Objective C (iOS).


UITableView allowsMultipleSelection

A Boolean value that determines whether users can select more than one row outside of editing mode.

@property(nonatomic) BOOL allowsMultipleSelection

Discussion of [UITableView allowsMultipleSelection]
This property controls whether multiple rows can be selected simultaneously outside of editing mode. When the value of this property is YES, a check mark is placed next to each row that is tapped. Tapping the row again removes the check mark. If you call indexPathsForSelectedRows, you can get the index paths that identify the selected rows.

The default value of this property is NO.

UITableView allowsMultipleSelection example.
self.tableView.allowsMultipleSelection=YES;

You are going to have to do the UITableViewCellAccessoryCheckmark manually in didSelectRowAtIndexPath and keep a track of which one is selected. I would recommend something like so:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableview cellAtIndex:indexPath];
    if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
       cell.accessoryType = UITableViewCellAccessoryCheckmark;
    else
     cell.accessoryType = UITableViewCellAccessoryNone;
}

Example of [UITableView allowsMultipleSelection].
Guys for multiple selection you just need

self.tableView.allowsMultipleSelection = YES;
on viewDidLoad and

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
    tableViewCell.accessoryView.hidden = NO;
    // if you don't use custom image tableViewCell.accessoryType = UITableViewCellAccessoryCheckmark;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *tableViewCell = [tableView cellForRowAtIndexPath:indexPath];
    tableViewCell.accessoryView.hidden = YES;
    // if you don't use custom image tableViewCell.accessoryType = UITableViewCellAccessoryNone;
}

UITableView allowsMultipleSelection example.
Tested with iOS4.3 - 6.0

-(void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {

    if ([controller.searchResultsTableView respondsToSelector:@selector(allowsMultipleSelectionDuringEditing)]) {
        controller.searchResultsTableView.allowsMultipleSelectionDuringEditing = YES;
    }
    else {
        controller.searchResultsTableView.allowsSelectionDuringEditing = YES;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellAccessoryCheckmark;
}

End of UITableView allowsMultipleSelection example article.