学习 UICollectionViewController 时,遇到了一个关于’UICollectionViewCell’类型转换的小问题,因为是新手,折腾了好久才搞明白原因。具体表现就是报错 “Could not cast value of type ‘UICollectionViewCell’ to TestProject.CollectionViewCell.”。
参考了网上很多资料,比如设置 Module,检查 DataSource 和 Delegates,最终终于发现了问题的原因。在我自定义的 CustomCollectionViewController
类中的 viewDidLoad()
函数中注册 cell 使用的类名是 UICollectionViewCell
,而在 cellForItemAt()
中 dequeueReusableCell()
返回的 cell 类名是 CustomCollectionViewCell
,两个 cell 类名不一致,所以会出现类型转换失败的问题。
两处类名保持一致就可避免此问题,正确的做法如下所示:
class CustomCollectionViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() // Register cell classes self.collectionView!.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCollectionViewCell // TODO return cell } }
参考链接:xcode – Could not cast value of type ‘UICollectionViewCell’ – Stack Overflow
Advertisements
分类:iOS