UITableView didSelectRowAtIndexPath add additional checkmark at tap

后端 未结 3 1216
青春惊慌失措
青春惊慌失措 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 08:09

    The problem you are facing is caused by cell reusing.

    Basically, if your UITableView has, let say 50 cells to display, it creates only 10 and then reuse them as you scroll down / scroll up. So whatever changes you did to the cell at row 0, it will be re-displayed for the row 11 as TableView uses the same cell etc.

    What you want to do is to keep track of which players have been selected independently from cell. You can achieve that easily by creating a collection, let say NSMutableArray or NSMutableDictionary, which will store BOOL values in NSNumber objects, eg.

    NSMutableArray *players = [NSMutableArray arrayWithCapacity:50];
    for (int i = 0; i < 50; i++) {
        [players addObject:[NSNumber numberWithBool:NO]];
    }
    

    Then in didSelectRowAtIndexPath:(NSIndexPath *)indexPath you do instead of operating on cell, you will simply change the value of a corresponding NSNumber object.

    Then in cellForRowAtIndexPath:(NSIndexPath *)indexPath you configure cell accessory by checking the corresponding entry in players collection.

    Or if you are really, really stubborn you could replace (THIS IS NOT RECOMENDED) the following line from the cellForRowAtIndexPath:(NSIndexPath *)indexPath:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    

    with:

    UITableViewCell *cell = nil;
    

提交回复
热议问题