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
相关产品推荐
相关产品推荐

