【问题标题】:FirebaseUI & SDWebImage Displaying Image in a for loop in a CollectionViewControllerCellFirebaseUI 和 SDWebImage 在 CollectionViewControllerCell 的 for 循环中显示图像
【发布时间】:2019-02-23 21:24:45
【问题描述】:

是否可以在 for 循环内为我的图像视图设置图像? 我目前正在从 firebase 数据库中获取所有图片下载 url,并将它们保存在 [[String: Any]]] 类型的字典中

在我的 CollectionViewControllerFile 的 cellforItemAt 方法中,我目前正在调用这样的 for 循环:

   override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyImageCell

    for myurl in urlArray {
        print("Hier kommt myURL \(myurl)")
    let url = URL(string: myurl["url"] as! String)
        cell.imageView?.sd_setImage(with: url, completed: nil)
    }

    cell.myLabel?.text  = "test"

    return cell
}

但这种方式只显示最后一张图片 5 次。

我在这里创建了一个自定义单元格并为其创建了一个类:

class MyImageCell: UICollectionViewCell {

@IBOutlet weak var imageView: UIImageView!

@IBOutlet weak var myLabel: UILabel!

}

我正在创建 1 个部分和每个部分 5 个项目。甚至可以在 for 循环中使用 SDWebImage 还是我做错了什么?

【问题讨论】:

    标签: ios swift firebase uicollectionview sdwebimage


    【解决方案1】:

    你需要

    let item = urlArray[indexPath.row]       
    let url = URL(string: item["url"] as! String)
    cell.imageView?.sd_setImage(with: url, completed: nil)
    

    每次调用 cellForItemAt 都会返回一个单元格,因此每次您最终将数组的最后一个 url 设置为 imageView 时,您还应该创建一个类似的模型

    struct Root {
      let url:URL
      // add more properties 
    }
    

    然后像这样创建一个数组

    var myArray = [Root]()
    

    【讨论】:

    • 成功了!非常感谢!
    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 2021-04-23
    • 2021-07-09
    • 1970-01-01
    • 2017-01-27
    • 2012-05-25
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多