集合视图单元格 scrollToItem 转换失败 [Swift]

Collection view cell scrollToItem cast fails [Swift]

在我的 swift 应用程序中,我有一个包含很多项目的集合视图,我想滚动到一个项目,然后设置集合视图单元格自定义的属性 class,但是演员表失败,为什么? 这是我的代码,我省略了一些明显的步骤,但结果是打印 "Cast fails":

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

}

扩展 ViewController: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()
        }
    }
}

转换失败,因为(该特定索引的)单元格在您查询时不可见

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

相反,您可以尝试设置 , at: .top, animated: false) 或将上述代码片段包装在 Dispatch after 块

顺便说一句,您最好更改数据源数组并重新加载该索引,这样您就不需要等待

// 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