首页 > 解决方案 > 无法将“UITableViewCell”(0x11e159aa0)类型的值转换为“test.CourseItemTableViewCell”

问题描述

我有一个带有表格视图单元格的表格视图。我正在尝试实现具有多种单元格类型的表格视图。当我这样做时,我收到以下错误

无法将“UITableViewCell”(0x11e159aa0)类型的值转换为“test.CourseItemTableViewCell”

if (indexPath.section == 0) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CourseItemTableViewCell

            cell.refreshUI()
            
            cell.cellIndex = indexPath
            cell.dataSource = self
            cell.delegate = self
            cell.backgroundColor = UIColor.clear
            cell.collectionView.reloadData()
            return cell;
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BookItemTableViewCell

            cell.refreshUI()
            
            cell.cellIndex = indexPath
            cell.dataSource = self
            cell.delegate = self
            cell.backgroundColor = UIColor.clear
            cell.collectionView.reloadData()
            return cell;
            
        }

如何在表格视图中实现多种单元格类型?我希望一行具有一种单元格类型,而另一行具有另一种单元格类型。

标签: iosswift

解决方案


也许是您没有注册两个单元格。这是我必须向您展示的内容:

我有一个UITableView动态显示任何三种类型的单元格... NSNumber、、CIColor和(未在此代码中显示)NSVector。根据自定义单元格,您有成对的标签和滑块 - 分别为 1、3 和 2。

将此限制为NSNumber(一个滑块)和CIColor(三个滑块),并使用正常工作的 subclassed UITableCells,我需要做的就是渲染这两个:

  1. 在 . 中正确注册两种单元格类型viewDidLoad。请注意,这是我认为您缺少的内容:

    tblAttributes.register(NSNumberCell.self, forCellReuseIdentifier: NSNumberCell.identifier)
    tblAttributes.register(CIColorCell.self, forCellReuseIdentifier: CIColorCell.identifier)
    
  2. 通过代码检测您要渲染的单元格类型tableView(cellForRowAt:)。注意,我的代码永远不应该返回UITableViewCell

    switch attributes[indexPath.row].attributeClass {
    case "NSNumber":
        let cell = tableView.dequeueReusableCell(withIdentifier: NSNumberCell.identifier) as! NSNumberCell
        // [populate label and slider defaults here]
        return cell
    case "CIColor":
        let cell = tableView.dequeueReusableCell(withIdentifier: CIColorCell.identifier) as! CIColorCell
        // [populate label and slider defaults here]
        return cell
    default:
        // this should never happen
        return UITableViewCell()
    }
    

总而言之,似乎CourseItemTableViewCellBookItemTableViewCell没有唯一标识。

以下是我对细胞进行子分类的方式:

class NSNumberCell:UITableViewCell {
    static let identifier = String(describing: NSNumberCell.self)

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        // [custom code here]
    }
}

其他自定义单元格也是如此。


推荐阅读