【问题标题】:Could not cast value of type 'UITableViewCell' (0x11e159aa0) to 'test.CourseItemTableViewCell'无法将“UITableViewCell”(0x11e159aa0)类型的值转换为“test.CourseItemTableViewCell”
【发布时间】:2020-09-01 14:57:32
【问题描述】:

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

无法将“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;
            
        }

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

【问题讨论】:

标签: ios swift


【解决方案1】:

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

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

将此限制为NSNumber(一个滑块)和CIColor(三个滑块),以及正常工作的子类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]
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多