0

I'm using a horizontal scrolling collectionView inside a tableView cell. I could do all the work but what I've encountered is that collectionView misses itself scrolled indexPath on tableView scroll. consider this: 1. I scroll inside collectionView of a cell(cell A) and move to indexPath with item 9 and section 0. 2. I scroll tableView and cell A goes off screen. 3. I scroll back and cell A will be displayed again. now collection of cell A has been reset and is in indexPath of item 0 and section 0.

how can i solve this to remain in item 9?

Hos Ap
  • 1,168
  • 2
  • 11
  • 24

3 Answers3

0

Actually it's not returning to zero index. It stays the same. BUT since tableView reuses all collection views, it replaced with another cell when it goes off screen and come back and inherits the position of the other collectionView.

So to fix this issue, tell the tableView to NOT reuse cells containing collection view. To achieve that, you must set different identifier for each cell.

Also you can store scrolling position on didEndDisplayingCell... and restore it on willDisplayCell.... but if cell is the middle of scrolling animation, it stops immediately.

I recommend you to try both ways and Test the memory usage and performance and pick what is best for you.

  • If I say tableView not to reuse cell, then performance significantly changes, isn't it? – Hos Ap Jul 16 '19 at 08:32
  • If you don't have so many cells (ex more than 20), you don't see visible performance hit. –  Jul 16 '19 at 08:34
  • I have pagination. so I think that could be more than 20 – Hos Ap Jul 16 '19 at 08:34
  • Cells will release some memory when they go off screen even if they don't reuse. But you can try the second option in my answer if you really care about reusing. –  Jul 16 '19 at 08:37
0

Try to use the following with the collection view:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    collectionView.scrollToItem(at: indexPath, at: [.centeredHorizontally,.centeredVertically], animated: true)
}
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
-1

There are two WorkArounds.

1 - Reset The UICollectionView offset position :

To Reset the collectionview position just call cell.collectionView.contentOffset = .zero in cellForRowAtIndexPath

2 - Maintain the previous scroll position :

To Maintain the previous scroll position, You'll need to have a list of offsets for each cell stored alongside your data models in the containing view controller. Then you might save the offset for a given cell in didEndDisplayingCell and setting it in cellForRowAtIndexPath instead of .zero

Taimoor Suleman
  • 1,588
  • 14
  • 29