Search code examples
iphoneuitableviewsdkcell

UITableViewCellAccessoryCheckmark multiple selection/detect which cells selected?


I have a UITableView that shows UITableView cells with the UITableViewCellAccessoryCheckmark option enabled. I would like to let the user select multiple cells to their liking and when their done, press a "Done" button.

However, when the "Done" button is pressed, I need to be able to add ONLY the selected object from the UITableView array into a separate array.

cell.accessoryType = UITableViewCellAccessoryCheckmark;

To recap: User can select as many cells as they want. When done, they press a UIButton which then adds ONLY the selected cells to another array.

Thank you for your help in advance!

UPDATE:

   -(void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [self.setupTable cellForRowAtIndexPath:indexPath];

    [self.selectedCells removeObject:[self.setupFeeds objectAtIndex:indexPath.row]];
    cell.accessoryType = UITableViewCellAccessoryNone;

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

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

    [self.selectedCells addObject:[self.setupFeeds objectAtIndex:indexPath.row]];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;


}

Solution

  • Your question does not relate to UITableViewCellAccessory or UITableView so the title is somewhat misleading.

    If I were you I would hold an NSMutableArray of selected cells as an instance variable or property.

    @property (nonatomic, strong) NSMutableArray *selectedCells;
    
    -(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //Maybe some validation here (such as duplicates etc)
        ...
        [self.selectedCells addObject:indexPath];
    
    }
    

    And then when done is pressed you may check this property to see which cells are selected.

    UPDATE:

    //Retrieve cell
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    //UITableViewCell has a textLabel property replace "yourLabel" with that if you have used it. Otherwise you can identify the label by subclassing tableviewcell or using tags.
    [self.selectedCells addObject:cell.yourLabel.text]; 
    
    //Then if cell is reselected
    
    [self.selectedCells removeObject:cell.yourLabel.text];