You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

继承SwipeTableViewController后TableView返回nil cell的问题求助

解决UITableView返回Nil Cell的问题

嘿,我来帮你排查这个错误的原因~你遇到的Error: UITableView dataSource returned a nil cell for row at index path.其实是因为继承关系和方法调用的问题,具体来说:

核心问题

你的CategoryViewController现在继承的是UIViewController,但你在cellForRowAt方法里调用了super.tableView(tableView, cellForRowAt: indexPath)——可是UIViewController本身并没有这个UITableView数据源方法,所以这个调用会返回nil,直接触发了错误。

正确的逻辑应该是让CategoryViewController继承自你写的SwipeTableViewController(因为它继承了UITableViewController,已经实现了基础的cell创建和滑动功能),这样调用super的方法才能拿到正确的cell实例。

修正后的代码

首先修改CategoryViewController的继承关系,并保持其余逻辑不变:

class CategoryViewController: SwipeTableViewController { // 改成继承SwipeTableViewController
    let realm = try! Realm() 
    var catArray: Results<Category>? 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
        return catArray?.count ?? 1 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
        // 调用super获取已配置滑动功能的cell
        let cell = super.tableView(tableView, cellForRowAt: indexPath) 
        // 设置cell的文本内容
        cell.textLabel?.text = catArray?[indexPath.row].name ?? "No Categories yet" 
        return cell 
    } 
}

SwipeTableViewController的代码可以保持不变:

class SwipeTableViewController: UITableViewController, SwipeTableViewCellDelegate { 
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell 
        cell.delegate = self 
        return cell 
    } 
}

额外检查项

  • 确认Storyboard中,CategoryViewController的类已经设置为CategoryViewController,并且TableView的原型cell标识符确实是Cell,cell的类是SwipeTableViewCell。
  • 因为SwipeTableViewController继承了UITableViewController,所以默认会自动作为TableView的dataSource和delegate,不用额外手动连接。

内容的提问来源于stack exchange,提问作者eyesplice17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:12:39