UITableView Multiple Checkmark Selection

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 19:17:55

You need to modify your cellForRowAtIndexPath to be the following:

// Assume cell is not checked -- if it is the loop below will check it.
[cell setAccessoryType:UITableViewCellAccessoryNone];
for (int i = 0; i < selectedIndexes.count; i++) {
        NSUInteger num = [[selectedIndexes objectAtIndex:i] intValue];

        if (num == indexPath.row) {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            // Once we find a match there is no point continuing the loop
            break;
        }
    }

You need to do this because a reusable cell might have the checkmark set -- so you need to clear it. Hope this helps.

Incidentally, using an NSSet would probably be a more elegant solution!

For multiple selection you just need on viewDidLoad

self.tableView.allowsMultipleSelection = YES;

and

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

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

No need to maintain separate array for storing selected rows. Use native method indexPathsForSelectedRows to get selected cells indexPath array. And just check arrayContains current IndexPath in cellForRow method as given below:

NSArray *indexPaths = [tableView indexPathsForSelectedRows];

if ([indexPaths containsObject:indexPath]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

#pragma mark- select/deselect 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [[self.tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[self.tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!