尝试使用此方法在 Collection View 中加载数据
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if urls.count == 0 {
return UICollectionViewCell()
}
let url = urls[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as! ImageCollectionViewCell
storageRef.reference(withPath: url).getData(maxSize: 15 * 1024 * 1024, completion: { data, error in
if let data = data {
cell.imageView.image = UIImage(data: data)
}
})
return cell
}
事情是 - 首先我可以看到两个没有数据的单元格,然后调用完成,我正在获取数据,但两个单元格中的第一个图像。 我怎样才能做对呢?我怎样才能同时获取元数据?
屏幕截图:
更新:
我写了一个数组
var datas = ["first", "second", "third", "fourth"]
将单元格代码更改为
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as! ImageCollectionViewCell
cell.nameLabel.text = datas[indexPath.item]
return cell
}
得到了这个:
还是看不出哪里出了问题。我重写的方法:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return datas.count / 2
}
最佳答案
我认为问题在于您正在下载 cellForItemAt indexPath: 函数中的信息,并且您应该在另一个类似这样的函数中下载图像
//Variable to store the UIImages
var images = [UIImage]()
//function to download the images, run it in the viewdidload like self.getImages()
func getImages(){
for url in self.urls{
storageRef.reference(withPath: url).getData(maxSize: 15 * 1024 * 1024, completion: { data, error in
if let data = data {
self.images.append(UIImage(data: data))
}
})
}
self.YourCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if urls.count == 0 {
return UICollectionViewCell()
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as! ImageCollectionViewCell
cell.imageView.image = self.images[indexPath.row]
return cell
}
关于ios - Firebase 存储数据显示两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134427/