问题
I have a UITableView with Dynamic Prototypes. I implemented the code below so that when I select a row, it will be marked and the previously selected row will be unmarked. However, for example, the row I selected is displayed in the middle of the screen, then when I scroll up or down, another cell (which is in the same middle position of the screen) is marked. In short, every view, there is a selected cell at the middle. Please advise.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *oldIndexPath = [self.tableView indexPathForSelectedRow];
[self.tableView cellForRowAtIndexPath:oldIndexPath].accessoryType = UITableViewCellAccessoryNone;
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
return indexPath;
}
回答1:
Probably you are overwriting accessoryType in your cellForRowAtIndexPath method - this is called each time table is about to draw new rows which were invisible before (as you described when you scroll up / down).
You need to handle it also in that function and update accessoryType there - otherwise it will randomly reuse a cells with different accessoryTypes.
回答2:
You are modifying just the visuals of cell, you're not updating the data model. Store the selected index path in a @property
somewhere, and adjust accessoryType
inside cellForRowAtIndexPath
.
来源:https://stackoverflow.com/questions/19251986/selecting-one-uitableviewcell-selects-the-other-cells-at-that-same-position-when