已获取数据但UITableView的cellForRowAt方法未执行,如何排查?
问题分析与排查方向
首先整理你提供的代码片段:
网络请求与数据赋值代码
extension ArticlesViewController { func setup() { self.navigationController?.navigationBar.prefersLargeTitles = true newtworkManager?.getNews { [weak self] (results) in switch results { case .success(let data): self?.articleListVM = ArticleListViewModel(articles: data.article!) // 测试打印 print(self?.articleListVM.articles as Any) DispatchQueue.main.async { self?.tableView.reloadData() } case .failure(let error): print(error.localizedDescription) } } } }
UITableView 数据源方法代码
extension ArticlesViewController { override func numberOfSections(in tableView: UITableView) -> Int { return self.articleListVM == nil ? 0 : self.articleListVM.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.articleListVM.numberOfRowsInSection(section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleTableViewCell", for: indexPath) as? ArticleTableViewCell else { fatalError("ArticleTableViewCell not found") } let articleVM = self.articleListVM.articleAtIndex(indexPath.row) cell.titleLabel.text = articleVM.title cell.abstractLabel.text = articleVM.abstract return cell } }
你提到已成功获取数据并打印,但cellForRowAt未执行,以下是具体排查方向:
1. 数据源计数方法返回值异常
cellForRowAt只有在numberOfSections返回大于0,且对应section的numberOfRowsInSection返回大于0时才会触发。
- 在
numberOfSections和numberOfRowsInSection中添加打印日志,确认返回值:override func numberOfSections(in tableView: UITableView) -> Int { let count = self.articleListVM == nil ? 0 : self.articleListVM.numberOfSections print("当前section数量:\(count)") return count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = self.articleListVM.numberOfRowsInSection(section) print("第\(section)组的row数量:\(count)") return count } - 若返回0,检查
ArticleListViewModel的numberOfSections和numberOfRowsInSection方法逻辑,是否错误返回0,或articles数组为空。
2. UITableView的数据源/代理未正确绑定
即使storyboard中关联了tableView,仍需确认:
- storyboard里tableView的
dataSource和delegate是否已拖线到ArticlesViewController; - 若代码中手动创建tableView,是否执行了
tableView.dataSource = self和tableView.delegate = self。
如果未绑定,所有数据源方法都不会被调用,自然不会触发cellForRowAt。
3. reloadData执行时articleListVM状态异常
在reloadData前添加打印,确认此时articleListVM的状态:
DispatchQueue.main.async { print("articleListVM是否为空:\(self?.articleListVM == nil)") print("文章数量:\(self?.articleListVM?.articles.count ?? 0)") self?.tableView.reloadData() }
若此时articleListVM为空,会导致numberOfSections返回0,无法触发cellForRowAt。
4. UITableView的显示区域异常
如果tableView的frame为CGRect.zero,或约束错误导致tableView不可见,即使有数据也不会触发cellForRowAt。可在reloadData后打印frame:
DispatchQueue.main.async { self?.tableView.reloadData() print("tableView frame:\(self?.tableView.frame ?? .zero)") }
内容的提问来源于stack exchange,提问作者Ahmed AlFailakawi
相关产品推荐
相关产品推荐

