UITableView didSelectRowAtIndexPath add additional checkmark at tap

后端 未结 3 1214
青春惊慌失措
青春惊慌失措 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 08:08

    I am using storyboards with Dynamic Prototype Cells to display a list of states I used some of the ideas above before I found this solution

    Step 1

    @interface StateViewController : UITableViewController
    {
        NSMutableArray *checkedIndexPaths;
    }
    

    Step 2

    (void)viewDidLoad
    {
        [super viewDidLoad];
        self.states = [[GAIGStateStore sharedInstance]allStates];
    
        //Setup default array to keep track of the checkmarks
        checkedIndexPaths = [NSMutableArray arrayWithCapacity:self.states.count];
        for (int i = 0; i < self.states.count; i++) {
            [checkedIndexPaths addObject:[NSNumber numberWithBool:NO]];
        }
    }
    

    Step 3

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
        //This toggles the checkmark
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
        if (cell.accessoryType == UITableViewCellAccessoryNone)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            //This sets the array
            [checkedIndexPaths replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    
        } else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
             //This sets the array
            [checkedIndexPaths replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
    
        }
    
    
    }
    

    Step 4

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:stateCell forIndexPath:indexPath];
    
        UILabel *stateLabel = (UILabel *)[cell viewWithTag:1000];
    
        StateProvince *myState = [self.states objectAtIndex:indexPath.row];
    
        stateLabel.text = myState.label;
    
        //Now set the check marks
        // Assume cell not checked;
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    
        NSNumber *num = [checkedIndexPaths objectAtIndex:indexPath.row];
    
    
        if (num == [NSNumber numberWithBool:YES]) {
               [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        }
    
    
        return cell;
    }
    

提交回复
热议问题