Swift新手运行旧教程代码遇UITableView返回nil cell崩溃如何解决
崩溃原因
报错提示已经明确说明:UITableView的数据源方法返回了空的cell。核心问题是你使用的是Swift 2及更早版本的cellForRowAtIndexPath方法签名,新版Swift中该数据源方法的命名已经调整,系统无法识别你写的旧版本方法,等同于你没有实现这个必填的数据源方法,因此触发崩溃。
修复步骤
第一步:替换为正确的数据源方法
将你现有的cellForRowAtIndexPath方法完全替换为以下代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "CoverPhotoCell", for: indexPath) as! CoverPhotoTableViewCell if let imageName = currentArticle?.coverPhoto { cell.coverImageView.image = UIImage(named: imageName) } return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "MainContentCell", for: indexPath) as! MainContentTableViewCell cell.titleLabel.text = currentArticle?.title cell.contentLabel.textAlignment = .left if let text = currentArticle?.mainContent { cell.contentLabel.attributedText = attributedContentFromText(text: text) } return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "SubContentCell", for: indexPath) as! SubContentTableViewCell if let article = currentArticle { let subContent = article.subContents[indexPath.row - 2] if let width = subContent.photoWidth, let height = subContent.photoHeight { let heightRatio = height / width cell.subImageViewHeight.constant = UIScreen.main.bounds.width * heightRatio } if let imageName = subContent.photo { cell.subImageView.image = UIImage(named: imageName) } cell.subContentLabel.textAlignment = .left if let text = subContent.text { cell.subContentLabel.attributedText = attributedContentFromText(text: text) } } return cell } }
第二步:检查cell配置
确认以下配置无误:
- 三个cell的重用标识符
CoverPhotoCell、MainContentCell、SubContentCell和你在Storyboard/XIB中填写的标识符完全一致,无拼写、大小写错误 - 每个cell的Class已经正确绑定到对应的自定义cell类
- 如果你是纯代码创建tableView,需要在
viewDidLoad中提前注册cell:
tableView.register(CoverPhotoTableViewCell.self, forCellReuseIdentifier: "CoverPhotoCell") tableView.register(MainContentTableViewCell.self, forCellReuseIdentifier: "MainContentCell") tableView.register(SubContentTableViewCell.self, forCellReuseIdentifier: "SubContentCell")
第三步(可选):添加兜底逻辑
如果需要避免极端场景下的崩溃,可以在方法最后添加默认cell兜底,确保永远不会返回空cell。
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

