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!)
// For testing
print(self?.articleListVM.articles as Any)
DispatchQueue.main.async {
self?.tableView.reloadData()
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
现在,在调试时,我成功地接收了数据并将其打印出来。但是,我意识到cellForRowAt函数没有被执行,这导致数据没有显示在表上。我看不出任何问题,但运行时当然不一致。
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
}
}
您认为该方法为什么没有被触发?请注意,情节提要上的UITableView和UITableViewCell分别连接到我的代码。我看不出它为什么不加载数据。
3条答案
按热度按时间iyzzxitl1#
确认ArticlesViewController为UITableViewDelegate & UITableViewDataSource协议并删除函数的重写。示例:
还要确保您已经通过故事板/代码连接了tableview。
whlutmcx2#
我的主要问题是全局变量
newtworkManager
。如代码所示:解决方法是删除此全局变量并替换为以下内容:
之后,cellForRowAt方法工作正常,数据单元格显示在UITableView上。
3zwjbxry3#
您是如何布局视图的,是通过编程还是通过Storyboard?
如果通过情节提要完成:
1.确保正确连接IBOutlet(检查是否有打字错误等),将委托和数据源分配给表视图并符合协议。
如果以编程方式完成:
1.确保在调用
tableView.reloadData()
之前设置了数据的委托和数据源