【问题标题】:Return Cell Based On Model Data In Switch Statement在 Switch 语句中根据模型数据返回单元格
【发布时间】:2021-07-26 10:58:39
【问题描述】:

我有一个拥有布尔值的模型。我想使用 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
    }
}

【问题讨论】:

  • 作为错误日志,我认为您的 TrueCell 存在问题:重用时它的标识符将返回 FalseCell 类型的单元格
  • 是的,你是对的,我已经使用 String(describing: Self) 声明了标识符,但是,我重命名了干扰标识符的自定义单元类。
  • 所以如果你有答案,你应该用答案更新问题并关闭这个问题
  • 肯定转换为 FalseCell 会导致错误。检查您的 FalseCell 是否为 FalseCell 类型。

标签: ios swift model collectionview indexpath


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2018-04-04
    • 2023-03-16
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多