我的collectionView从Firebase获取数据。这是一个firebase变量,用于设置单元格数量,并获取使用SDWebImage下载的单元格图像的下载链接。它为每个单元格下载的图像大约为60千字节,但收集视图大约需要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
}
答案 0 :(得分:1)
不要将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 */
}
}