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 分別連接到我的代碼。我看不出它沒有加載資料的原因。
uj5u.com熱心網友回復:
將 ArticlesViewController 確認為 UITableViewDelegate 和 UITableViewDataSource 協議并洗掉函式的覆寫。例子:
extension ArticlesViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return self.articleListVM == nil ? 0 : self.articleListVM.numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
....
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
....
}
}
還要確保您已通過故事板/代碼連接了您的表格視圖。
tableView.dataSource = self
tableView.delegate = self
uj5u.com熱心網友回復:
您是如何以編程方式或通過 Storyboard 布置視圖的?
如果通過 Storyboard 完成,請確保正確連接 IBOutlet(檢查拼寫錯誤等),將委托和資料源分配給表格視圖并遵守協議。
tableview.translatesAutoresizingMaskIntoConstraints = false如果以編程方式完成,請確保將表視圖作為子視圖添加到父視圖,通過添加約束(確保設定)或設定框架來布置表視圖。
uj5u.com熱心網友回復:
我的主要問題是全域變數newtworkManager,正如您在代碼中看到的那樣:
newtworkManager?.getNews {...}
解決方案是我洗掉了這個全域變數并將其替換為以下內容:
NetworkManager().getNews { ...}
之后,cellForRowAt 方法作業正常,資料單元格顯示在 UITableView 上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/529364.html
