Monday, July 27, 2009

Multiple Row Selection with UITableView — The Easy Way

Cocoa with Love introduced the hard way to implement multiple row selection for 2.x firmware. On 3.x, there is a much easier way to do the same, if you dare you embrace undocumented methods.

Multi-selection is regarded as one of the editing style. Therefore, to make a cell multi-selectable, implement this in your UITableViewDelegate:
-(UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath {
...
return 3;
}

The "3" here means multiselection. The result is like this:


To get the selected rows, call the -indexPathsForSelectedRows method on the table view.
NSArray* selectedRows = [tableView indexPathsForSelectedRows];


If you dislike the red check mark, you can use the undocumented multiselectCheckmarkColor property to change it. Unfortunately, it has to be applied on the whole table.
tableView.multiselectCheckmarkColor = [UIColor blueColor];

The light blue background color cannot be changed unless you subclass or categorize UITableViewCell and override the -_multiselectBackgroundColor method, like this:
-(UIColor*)_multiselectBackgroundColor { return [UIColor yellowColor]; }

4 comments:

  1. KennyTM~, sorry this comment is not related to the post, but I would really like an update on your calculator search bundle. You indicated that the search framework had changed slightly in 3.0 final. Have you had the time to figure out what changed? Thanks for all your hard work!

    ReplyDelete
  2. @Greg:

    The bundle itself has no problem working I can imagine, but the _injection mechanism_ does not work because no more searchBundle can be included, as Apple's internal ones already occupied them all. I know iFile4iPhone is already working on it.

    ReplyDelete
  3. I am trying:
    tableView.multiselectCheckmarkColor = [UIColor blueColor];

    but that is giving me:
    Request for member 'multiselectCheckmarkColor' in something not a structure or union

    (It is my tableview that I am trying it on, as if I change multiselectCheckmarkColor to say scrollsToTop, then its fine)

    I also tried [tableView setMultiselectCheckmarkColor: [UIColor blueColor]];

    Which compiles but gives a warning (of course) since its undocumented.

    However this does not change the color of the checkmark. It still shows as red.

    Any idea why this wouldnt be working?

    ReplyDelete
  4. [self.tableView setMultiselectCheckmarkColor:[UIColor greenColor]];

    ReplyDelete