iOS tableView multiple selection

916 views Asked by At

Many of the ways and methods out there to select multiple rows is either deprecated or doesn't work.

I simply want to select multiple rows in didSelectRowAtIndexPath and save them into Array or NSUserDefault. This case I picked NSUserDefault but I am willing to change it to Array.

This is my code:

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

    NotificationsTableViewCell *cell = (NotificationsTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];

    //set clicked icon after row selected
    cell.imgIcon.image=[UIImage imageNamed:@"select-icon"];

    //notification id for selected row
    Notifications* selected = notifications[indexPath.section];
    selectedGroup = selected.NotificationsId;

     //save it in nsuserdefaults
    [[NSUserDefaults standardUserDefaults] setObject:selectedGroup forKey:@"notificationSelectedID"];

}

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

//deselect the row

}

Note: I am using latest Xcode SDK 8.

Thank you for your helps.

2

There are 2 answers

2
user3575114 On

You can declare mutable array and when every time user selects particular row, add required detail for particular row in an array then use NSUserDefaults to store updated array.

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

[arrRows addObject:[NSString stringWithFormat:@"%@", indexPath]];
[[NSUserDefaults standardUserDefaults] setValue:arrRows forKey:@"arrRows"];

}

5
Nitin Gohel On
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

NotificationsTableViewCell *cell = (NotificationsTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];

 // do your logic with following condition

if (cell.accessoryType == UITableViewCellAccessoryNone) 
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    } 
    else 
    {

        cell.accessoryType = UITableViewCellAccessoryNone;

    }

}