UITableView didSelectRowAtIndexPath add additional checkmark at tap

后端 未结 3 1212
青春惊慌失措
青春惊慌失措 2021-02-10 07:17

When i select a player in \'didSelectRowAtIndexPath\' and add a checkmark on the selected row it adds an additional checkmark.

If i tap row = 0 it adds a checkmark to ro

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 07:55

    For others coming here (like I did) to see why their table selects random cells, you have to add something like the following to your cellForRowAtIndexPath:

    // Assume cell not checked;
    [cell setAccessoryType:UITableViewCellAccessoryNone];
    for (int i = 0; i < checkedIndexPaths.count; i++) {
        NSUInteger num = [[checkedIndexPaths objectAtIndex:i] row];
    
        if (num == indexPath.row) {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        }
    }
    

    I keep a NSMutableArray called checkedIndexPaths so that I know which indexPaths are checked. Keeping such an array allows you to easily limit the number of cells a user can check. Here's an example of my didSelectRowAtIndexPath:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
        // uncheck if already checked
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [checkedIndexPaths removeObject:indexPath];
        }
        else {
            // make sure no more than 3 are selected
            if ([checkedIndexPaths count] < 3) {
    
                // check row
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                // add it to our list of checked indexes
                [checkedIndexPaths addObject:indexPath];
            } else {
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Note" 
                                                                message:@"You can only select 3 rows." 
                                                               delegate:nil 
                                                      cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
            }
        }  
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    

提交回复
热议问题