首页 > 解决方案 > 在 Switch 语句中根据模型数据返回单元格

问题描述

我有一个持有布尔值的模型。我想使用 switch 语句根据模型中 bool 的值返回 UICollectionViewCell 。但是,我遇到了一个铸造错误。

Could not cast value of type 'Project.FalseCell' (0x10077a9f0) to 'Project.TrueCell' (0x100777ef8).

我检查了以下内容;

  1. 我已经注册了我的细胞viewDidLoad
  2. 我对每种细胞类型都有唯一的标识符

我在这里想念什么?

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

标签: iosswiftmodelcollectionviewindexpath

解决方案


根据@goat_herd 的评论,使用单元标识符存在问题,String(describing: Self)因为我曾一度重命名该类,这导致标识符中断。

我将标识符更改为原始值字符串,这解决了这个问题。


推荐阅读