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

UITableView的cellForRowAt方法报Missing return UITableViewCell错误如何解决?

问题根因
  • 方法用途错配:你当前编写的tableView(_:cellForRowAt:)是UITableViewDataSource协议的强制方法,核心作用是生成、配置并返回对应索引位置的UITableViewCell实例,必须有返回值,你把单元格点击跳转的业务逻辑写进了这个方法里,完全不符合方法设计用途。
  • 协议归属错误:你把属于DataSource协议的cellForRowAt方法写进了UITableViewDelegate的扩展中,本身就不符合协议实现规范。
  • 跳转逻辑放错位置:单元格点击后的跳转逻辑应该放在tableView(_:didSelectRowAt:)方法中,这个方法是UITableViewDelegate的可选方法,无返回值,专门用于响应单元格点击事件。
正确实现代码

1. 拆分UITableViewDataSource扩展,实现cell生成逻辑

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 此处替换为你自己注册的cell复用标识
        let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID", for: indexPath)
        // 按需配置cell的展示内容,比如文本、图片等
        cell.textLabel?.text = tasks[indexPath.row].title
        return cell
    }
}

2. 调整UITableViewDelegate扩展,实现点击跳转逻辑

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let vc = storyboard?.instantiateViewController(identifier: "tasks") as! TaskViewController
        vc.title = "New Tasks"
        vc.task = tasks[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 03:36:08