【发布时间】:2017-09-08 13:17:43
【问题描述】:
我目前正在跟随指南 (creating custom tableview cells in swift) 在 Swift 中为 UITableView 创建自定义单元格。但是,我在运行项目时遇到了错误。下面是触发错误的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// ***** Error triggers on the line below ******
let cell:MyCustomCellModel = self.plantList.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCellModel
cell.plantImage.backgroundColor = self.colors[indexPath.row]
cell.plantLabel.text = self.animals[indexPath.row]
return cell
}
我的问题与其他 stackoverflow 帖子(即:Could not cast value of type 'UITableViewCell' to '(AppName).(CustomCellName)')中描述的问题相同,但是其中没有一个解决方案能够解决我的问题。
这是我为解决此问题所做的各种尝试。
-
我已经尝试了以下两种代码解决方案来注册我的类(我将其放入 viewdidload 方法中),但都没有提供修复:
self.plantList.register(MyCustomCellModel.self, forCellReuseIdentifier: "cell") self.plantList.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
我还尝试了许多对有关此问题的各种 stackoverflow 帖子中提到的人有用的小修复,但没有一个对我有用。
任何提示将不胜感激。如果需要任何其他源代码来调试它,我很乐意发布它。
【问题讨论】:
-
self.plantList.dequeueReusableCell...vstableView.dequeueReusableCell...你能检查一下self.plantList是否确实是该方法的tableView参数吗?否则,请尝试也调用func dequeueReusableCell(withIdentifier:, for:),(使用 IndexPath)。 -
是的,self.plantList 是 tableView 参数。我尝试将 func 与 ', for: indexPath' 一起使用,这给了我同样的错误。
-
情节提要中的单元格 ID 和“cellReuseIdentifier”是否相同?
-
是的!这行代码是:let cellReuseIdentifier = "cell"
-
故事板中可能有第二个单元原型,标识符为“单元”。三重检查。
标签: swift xcode uitableview swift3