Search code examples
iosuitableviewuicollectionviewuicollectionviewlayout

UICollectionView inside UITableViewCell default contentOffset


In my app I have a tableView which contains several cells with UICollectionView, The layout of UICollectionView is custom and set in cellForRowAtIndexPath.

In prepare method of collectionViewLayout I set a default contentOffset to collectionView.

But this contentOffset only works for visible table cells and when I scroll tableview other cells do not have this default content offset.

How to fix this issue ?

override func prepare() {
    guard cache.isEmpty, let collectionView = collectionView else {
        return
    }

    // ...
    // Prepare cell attributes and add to cache array
    // ...

    collectionView.contentOffset = CGPoint(x: 100, y:0)
}

Solution

  • I used the following solution to fix this issue, Set content offset after a few milliseconds delay fixed this issue.

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(10), execute: {
        collectionView.contentOffset = self.initialContentOffset!
    })
    

    But I think this isn't the best solution but I couldn't find another solution to fix this issue