首页 > 解决方案 > retain scroll position for nested collectionView

问题描述

After the tableView.reloadData() the visible collectionView display the first row unexpected immediately.

Im building a tableView contains collectionView in its cells, users can scroll multiple images in every single tableView just like Instagram. How can I fix it? Thanks!

tableView DataSource

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
}

prepareForReuse Method in tableViewCell

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
}

DataSource of collectionView inside tableViewCell

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
}

Like the question title said. I expect the visible collectionView stays on the current row after the tableView load more data after tableView.reloadData() is called! Thanks again!

标签: iosswiftuitableviewcollectionview

解决方案


我认为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
}

推荐阅读