UICollectionView inside UITableViewCell default contentOffset

UICollectionView inside UITableViewCell default contentOffset

在我的应用程序中,我有一个 tableView,其中包含多个带有 UICollectionView 的单元格,UICollectionView 的布局是自定义的并在 cellForRowAtIndexPath 中设置。

collectionViewLayoutprepare 方法中,我将默认的 contentOffset 设置为 collectionView。

但是这个 contentOffset 只适用于可见的 table 单元格,当我滚动 table 查看其他单元格时没有这个 default content offset

如何解决这个问题?

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)
}

我使用以下解决方案解决了这个问题,延迟几毫秒后设置内容偏移解决了这个问题。

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

但我认为这不是最佳解决方案,但我找不到解决此问题的其他解决方案