下面是我的 ViewController 的代碼
class NewsViewController: UIViewController {
let networkManager = NetworkManager()
var newsArray = [NewsModel]()
var totalResult:Int = 0
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
networkManager.fetchNewsData(forCoutry: "us", category: "business") { newsDataModel in
self.totalResult = newsDataModel.totalResults
for article in newsDataModel.articles {
let news = NewsModel(newsTitle: article.title,
urlToNewsWebSite: article.url,
authorWebSiteName: article.source.name,
urlToImage: article.urlToImage ?? "" )
self.newsArray.append(news)
}
}
collectionView.reloadData()
}
}
extension NewsViewController: UICollectionViewDelegate {
}
extension NewsViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! NewsCell
cell.configureCell()
cell.initData(news: newsArray[indexPath.item])
collectionView.reloadData()
return cell
}
}
我需要從網路請求資料,然后在completion Handler中回圈處理它們,并填充newsArray = [NewsModel](),然后才初始化單元格
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! NewsCell
cell.configureCell()
cell.initData(news: newsArray[indexPath.item])
collectionView.reloadData()
return cell
但首先,單元格為我初始化,然后來自完成處理程式的代碼開始作業,我使用斷點計算出來。
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
您應該回傳newsArray此處的長度:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return newsArray.count
}
cellForItemAt如果newsArray為空(例如初始時),這將導致不會被呼叫。
接下來,您應該將reloadData呼叫移動到完成處理程式內部,以便在擁有專案之后cellForItemAt呼叫。 newsArray
networkManager.fetchNewsData(forCoutry: "us", category: "business") { [weak self] newsDataModel in
self?.totalResult = newsDataModel.totalResults
for article in newsDataModel.articles {
let news = NewsModel(newsTitle: article.title,
urlToNewsWebSite: article.url,
authorWebSiteName: article.source.name,
urlToImage: article.urlToImage ?? "" )
self?.newsArray.append(news)
}
// notice this:
self?.collectionView.reloadData()
}
uj5u.com熱心網友回復:
您應該在 completionHandler 中添加 collectionView.reload 資料(在主佇列中調度)。另外,不要在 cellForRow 中重新加載 collectionView,因為它可能會導致無限回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361692.html
