user678145
user678145

Reputation: 109

collectionview in tableviewcell displays wrong data when reuse happens

I am encountering a problem during the reuse of tableViewCells.

I have a TableView. Each tableviewcell contains a UIView that holds a collection view. The datasource and delegate are set to that view. Each cell of that collection view displays one image.

When I am scrolling now my tableview, the cells of the tableview are reused. In the cellForRowAtIndexPath I am setting the values of the cell (i.e. also for the delegate and datasource of the collection view).

However, the reused cells do not update the images contained in the collectionviewcell. I already tried different positions for self.setNeedsDisplay() without success.

Anybody has any suggestions where to trigger the correct reload?

BR Dominik

Upvotes: 4

Views: 2556

Answers (2)

a.tarasevich
a.tarasevich

Reputation: 201

Probably you can find the answer under my the same question

It's probably because of the reuse system of cells in UITableView.

You should call it in the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell where you configure your cell. This way, each time a cell is reused, you update its content.

You also have to clean your datasource and delegate, because it's a reused cell so it may already have been used with another value.

Upvotes: 1

totiDev
totiDev

Reputation: 5285

You should set the data in the cellForItemAtIndexPath. But you should also override the prepareForReuse() method in your cells, and reset everything there - this will get called before reusing the cell. For instance in your cell you should set the image to nil and the delegate to nil.

Upvotes: 4

Related Questions