我的 collectionView 从 Firebase 获取数据。有一个 firebase 变量来设置单元格的数量并获取使用 SDWebImage 下载的单元格图像的下载链接。它为每个单元格下载的图像大约为 60 KB,但 collectionview 的加载时间约为 5 秒。此外,当它确实加载时,它会将所有细胞图像显示为第一个细胞图像,然后在一秒钟后更改为正确的图像。
我正在使用 swift 3
这是我的代码
override func viewDidLoad() {
super.viewDidLoad()
//firebase
FIRDatabase.database().reference(withPath: "Radio").child("numCells").observeSingleEvent(of: .value, with: { (snapshot) in
if let snapInt = snapshot.value as? Int {
self.numCells = snapInt
self.collectionView?.performBatchUpdates(
{
self.collectionView?.reloadSections(NSIndexSet(index: 0) as IndexSet)
}, completion: { (finished:Bool) -> Void in
})
}
}) { (error) in
print(error.localizedDescription)
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return numCells
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
let icon = cell.viewWithTag(3) as! UIImageView
//Firebase
FIRDatabase.database().reference(withPath: "Icons").child("img\(indexPath.row)").child("imgLink").observeSingleEvent(of: .value, with: { (snapshot) in
if let snapString = snapshot.value as? String {
icon.sd_setShowActivityIndicatorView(true)
icon.sd_setIndicatorStyle(.gray)
icon.sd_setImage(with: URL(string: snapString))
}
}) { (error) in
print(error.localizedDescription)
}//firebase end
return cell
}
最佳答案
不要将 cellForItemAtIndexPath
用于繁重的请求:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
FIRDatabase.database().reference(withPath: "Icons").child("img\(indexPath.row)").child("imgLink").observeSingleEvent(of: .value, with: { [weak collectionView] (snapshot) in
guard let collectionView = collectionView else { return }
let cell = collectionView.cellForItem(at: indexPath)
/* do whatever you need with cell */
}) { (error) in
/* handle error */
}
}
关于ios - CollectionView 加载缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055872/