集合视图单元格 scrollToItem 投放失败 [Swift] 。

问题描述 投票:0回答:1

在我的swift应用中,我有一个有很多项目的集合视图,我想滚动到一个项目,然后设置一个集合视图单元格自定义类的本体,但是投递失败,为什么? 这是我的代码,我省略了一些明显的步骤,但结果是打印 "投递失败"。

class ViewController: UIViewController {

lazy var collectionView: UICollectionView = {
    let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
    cv.backgroundColor = .gray
    cv.register(Cell.self, forCellWithReuseIdentifier: Cell.id)
    cv.delegate = self
    cv.dataSource = self
    return cv
}()

}

extension ViewController.UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.id, for: indexPath) as! Cell
    cell.backgroundColor = .purple
    cell.label.text = "\(indexPath)"
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if indexPath.item == 14 {
        collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .top, animated: true)
        guard let cell = collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? Cell else {
            print("Cast fails")
            return
        }
        cell.label.text = "Something"
    }
}

}

这是我找到的解决方案。

extension UICollectionView {
    func scrollToItem(at indexPath: IndexPath, at position: UICollectionView.ScrollPosition, completion: @escaping () -> ()) {
        scrollToItem(at: indexPath, at: .top, animated: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            completion()
        }
    }
}
swift uicollectionview uicollectionviewcell uicollectionviewlayout
1个回答
0
投票

投放失败,因为在你查询单元格的时候,该单元格(该特定索引的)是不可见的。

guard let cell = collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? Cell else {
  print("Cast fails")
  return
} 

相反,你可以尝试设置 , at: .top, animated: false) 或者在块后的Dispatch中封装上述代码片段

顺便说一下,你最好改变dataSource数组,然后重新加载那个索引,这样你就不需要等待了。

// change source array at that index
// scroll to that row with/without animation
// make sure you set value for the cell label in cellForRowAt table's datasource method 
© www.soinside.com 2019 - 2024. All rights reserved.