【发布时间】:2022-11-12 21:11:21
【问题描述】:
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 分别连接到我的代码。我看不出它没有加载数据的原因。
【问题讨论】:
-
您是否在 viewDidLoad() 中设置了委托? tableView.delegate = self tableView.dataSource = self
-
@NomanUmar 是的,已经这样做了,但根本无法工作。
-
如果 numberOfRowsInSection > 0 & numberOfSections >= 1,我会仔细检查你的约束。作为尝试,您可以在设置中添加
tableView.rowHeight = 50并查看它是否被调用 -
@AhmedAlFailakawi 如果问题出在返回 numberOfRowsInSection 中的 0 个原始文件或返回 numberOfSections 中的 0 个部分,并且您发现您的错误并且问题已解决 - 请关闭您的问题。
标签: ios swift uitableview uikit