保留嵌套 collectionView 的滚动位置

retain scroll position for nested collectionView

tableView.reloadData() 之后可见 collectionView 立即显示意外的第一行。

我正在构建一个 tableView 在其单元格中包含 collectionView,用户可以在每个 tableView 中滚动多个图像,就像 Instagram 一样。我该如何解决?谢谢!

tableView 数据源

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return photoRolls.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! HomeTableViewCell
    if photoRolls.isEmpty {
        return UITableViewCell()
    }        
    let user: UserModel = users[indexPath.row]
    let photoRoll: PhotoRoll = photoRolls[indexPath.row] //this Model contains post info: likes, comments etc.
    let photoUrls: UrlStrings = urls[indexPath.row] //this Model contains a array of urlStrings for each collectionView inside the tableViewCell
    cell.urlStrings = photoUrls
    cell.photoRoll = photoRoll
    cell.user = user

    cell.delegate = self

    return cell
}

tableViewCell中的prepareForReuse方法

override func prepareForReuse() {
    super.prepareForReuse()
    captionLabel.text = nil
    profileImage.image = UIImage(named: "placeholderImg")
    profileImageRight.image = UIImage(named: "placeholderImg")
    collectionView.scrollToItem(at:IndexPath(item: 0, section: 0), at: .left, animated: false)//tried to remove this method, but the collectionView  would not display the first row when it's visible
}

tableViewCell 中 collectionView 的数据源

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return cellUrlArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell
    cell.url = cellUrlArray[indexPath.row]
    return cell
}

如题名所说。我希望在调用 tableView.reloadData()tableView 加载更多数据后可见 collectionView 保留在当前行!再次感谢!

我认为 contentOffset 缓存是可行的,如下所示

var cachedPosition = Dictionary<IndexPath,CGPoint>()

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if let cell = cell as? HomeTableViewCell {
        cachedPosition[indexPath] = cell.collectionView.contentOffset
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    <<Your Code>>

    cell.collectionView.contentOffset = cachedPosition[indexPath] ?? .zero        
    return cell
}