【发布时间】:2021-07-26 10:58:39
【问题描述】:
我有一个拥有布尔值的模型。我想使用 switch 语句根据模型中 bool 的值返回 UICollectionViewCell 。但是,我遇到了投射错误。
Could not cast value of type 'Project.FalseCell' (0x10077a9f0) to 'Project.TrueCell' (0x100777ef8).
我已经检查了以下内容;
- 我已经在
viewDidLoad注册了我的细胞 - 我对每种细胞类型都有唯一的标识符
我在这里错过了什么?
// MODEL
struct Model {
let bool: Bool
}
// CONTROLLER
let models = [Model]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = models[indexPath.item]
switch model.bool {
case true:
let trueCell: TrueCell = listView.collectionView.dequeueReusableCell(withReuseIdentifier: TrueCell.identifier, for: indexPath) as! TrueCell
return trueCell
case false:
let falseCell: FalseCell = listView.collectionView.dequeueReusableCell(withReuseIdentifier: FalseCell.identifier, for: indexPath) as! FalseCell
return falseCell
}
}
【问题讨论】:
-
作为错误日志,我认为您的 TrueCell 存在问题:重用时它的标识符将返回 FalseCell 类型的单元格
-
是的,你是对的,我已经使用 String(describing: Self) 声明了标识符,但是,我重命名了干扰标识符的自定义单元类。
-
所以如果你有答案,你应该用答案更新问题并关闭这个问题
-
肯定转换为 FalseCell 会导致错误。检查您的 FalseCell 是否为 FalseCell 类型。
标签: ios swift model collectionview indexpath