【问题标题】:Images not displayed in collection view cell图像未显示在集合视图单元格中
【发布时间】:2018-01-12 12:56:58
【问题描述】:

我有一个集合视图单元格,里面有一个 imageView。在它上面我使用sd_setImage 显示图像数组,一旦从firestore 加载。在控制台中,我看到了我的应用下载的所有图像。

我使用这个代码:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newDetailCollectionCell", for: indexPath) as! NewDetailCollectionViewCell
    cell.imageView.sd_setImage(with: URL(string: images[indexPath.item]))

    return cell
}

当我使用此代码时,我看不到我的图像。但是,如果我使用下面的代码,一切正常。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newDetailCollectionCell", for: indexPath) as! NewDetailCollectionViewCell
    cell.imageView.sd_setImage(with: URL(string: images[indexPath.item]))

    return cell
}

【问题讨论】:

  • 你可以在 numberOfItemsInSection 处设置断点并打印“images.count”吗?
  • 请添加整个代码。
  • @VDPurohit 如果我打印 images.count 我看到 1 个项目。但我仍然有 tableView 和 tableView 向我展示了 images.count = 10
  • @KeyurHirani 我添加了代码,我认为不需要更多代码来解决问题
  • 我在控制台中看到所有图像,但为什么我的图像不想出现?我在 mainstoryboard 中所做的委托和数据源

标签: ios swift xcode


【解决方案1】:

问题是您应该在Dispatch.main.async {} 中调用collectionView.reloadData() 而不是tableView.reloadData(),因为在这种情况下collectionView 需要更新数据源。我希望这会有所帮助。

DispatchQueue.main.async {
  self.collectionView?.reloadData()
}

【讨论】:

  • 我发现了问题所在。你说的没有帮助,但它帮助我理解了我有什么问题。谢谢。
  • @Dima 你介意分享你的问题吗?我也有类似的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 2021-01-31
  • 1970-01-01
  • 2013-10-14
  • 2016-12-06
相关资源
最近更新 更多