【发布时间】:2020-05-04 16:04:11
【问题描述】:
在我的 swift 应用程序中,我有一个包含很多项目的集合视图,我想滚动到一个项目,然后设置 collectionview 单元格自定义类的适当性,但转换失败,为什么? 这是我的代码,我省略了一些明显的步骤,但结果是打印“Cast failed”:
类视图控制器: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()
}
}
}
【问题讨论】:
标签: swift uicollectionview uicollectionviewcell uicollectionviewlayout