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)
}
}
}
Now, while debugging, I am receiving data successfully and printing it out. However, I realized the cellForRowAt function is not being executed which is causing the data not showing on the table. I cannot see any issue, but the run time disagrees of course.
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
}
}
Why do you think this method is not getting triggered? Note that my UITableView and UITableViewCell on the storyboard are connected respectively to my code. I see no reason why it is not loading the data.
3
Answers
My main issue was with the global variable
newtworkManager
And as you can see in code:The solution was that I deleted this global variable and replaced it with the following:
After that, cellForRowAt method was working fine and data cells were displayed on the UITableView.
Confirm ArticlesViewController to UITableViewDelegate & UITableViewDataSource protocol & remove override for functions.
Example:
Also make sure you have connected your tableview via storyboard/code.
How have you layed out the views, programmatically or via Storyboard?
If done via Storyboard:
assign delegate & datasource to the tableviews and conform to the
protocols.
If done programmatically:
Make sure you set the delegate and datasource of the data before
calling
tableView.reloadData()