ios - 无法将“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;
}
如何在表格视图中实现多种单元格类型?我希望一行具有一种单元格类型,而另一行具有另一种单元格类型。
解决方案
也许是您没有注册两个单元格。这是我必须向您展示的内容:
我有一个UITableView
动态显示任何三种类型的单元格... NSNumber
、、CIColor
和(未在此代码中显示)NSVector
。根据自定义单元格,您有成对的标签和滑块 - 分别为 1、3 和 2。
将此限制为NSNumber
(一个滑块)和CIColor
(三个滑块),并使用正常工作的 subclassed UITableCells
,我需要做的就是渲染这两个:
在 . 中正确注册两种单元格类型
viewDidLoad
。请注意,这是我认为您缺少的内容:tblAttributes.register(NSNumberCell.self, forCellReuseIdentifier: NSNumberCell.identifier) tblAttributes.register(CIColorCell.self, forCellReuseIdentifier: CIColorCell.identifier)
通过代码检测您要渲染的单元格类型
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() }
总而言之,似乎CourseItemTableViewCell
并BookItemTableViewCell
没有唯一标识。
以下是我对细胞进行子分类的方式:
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]
}
}
其他自定义单元格也是如此。
推荐阅读
- reporting-services - SSRS 报告自定义排序行
- java - Windows Server 2016 中的字符集不显示法语字符
- javascript - windows和mac上的事件键相同吗?
- java - 如何在链表的节点上插入数组
- c# - 如何检查 Unity 的 UI 中是否存在按钮组件?
- c# - 在父表单中启动子表单后,父表单中标签的透明度消失(变为灰色)
- android - 通过 getSystemService 请求 NSD_SERVICE 时应用程序无响应
- regex - 为什么我不能将 ^\s 与 grep 一起使用?
- laravel-5 - Laravel Spatie/Newsletter 不在 Mailchimp 中添加联系人
- python - 提取 2 个特定标签之间的行