UITableViewCell, two cells receive accessory

Situation: when the user selects a cell, a button is added to this cell. When they select a new cell, the button is removed from the previous cell and added to the new cell. It works. The problem is that more data is added to the table. So let's say that there are 20 cells, then I add another 20 cells. Then I select the first cell, but the button is added to cell 1 and cell 21. The select delegate method registers only the first one selected.

From my didSelectRowAtIndexPath method:

if (self.selectedCell) { self.selectedCell.accessoryView = nil; self.selectedCell = nil; } UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [downloadButton setTitle:@"Download" forState:UIControlStateNormal]; [downloadButton setFrame:CGRectMake(0, 0, 130, 34)]; self.selectedCell = [self.tableView cellForRowAtIndexPath:indexPath]; self.selectedCell.accessoryView = downloadButton; [self.selectedCell setNeedsDisplay]; 

In my method, which adds more data to the table, I end up:

 if(self.selectedCell){ self.selectedCell.accessoryView = nil; self.selectedCell = nil; } [self.tableView reloadData]; [self.tableView setNeedsLayout]; 
+4
source share
1 answer

Cells are reused. In cellForRowAtIndexPath: you forget to clear the accessoryView . When a cell is reused, an accessoryView appears.

I like to configure accessoryView in tableView:willDisplayCell:forRowAtIndexPath: This is called just before the cell is placed on the screen. Then you can do something like:

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if (cell.isSelected) { cell.accessoryView = self.downloadButton; // No reason to create a new one every time, right? } else { cell.accessoryView = nil; } } 
+5
source

All Articles