【问题标题】:Why UICollectionViewCell images are not loaded although the image var is not nil in debugger?为什么 UICollectionViewCell 图像未加载,尽管图像变量在调试器中不是 nil?
【发布时间】:2019-11-02 12:42:44
【问题描述】:

我正在使用集合视图来显示新闻应用程序中的类别选择。 我的收藏视图图像未加载到单元格中。在检查调试器时,图像变量包含图像。 图片将从 Assets.xcassets 文件夹中加载。 在调试器中打印单元格视图的图像值时,它显示为零。

PS:单元格及其标签加载正常,只是 .png 图像没有加载。

import UIKit

class CategoriesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var categoriesCollectionView: UICollectionView!
    private var newsCategories = ["Buisness","Sports","Health","Science","Entertainment","Technology","General","Everything"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        categoriesCollectionView.delegate = self
        categoriesCollectionView.dataSource = self
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoriesCollectionViewCell", for: indexPath) as? CategoriesCollectionViewCell{
            cell.imageView.image = UIImage(contentsOfFile: newsCategories[indexPath.item])
            cell.label.text = "\(newsCategories[indexPath.item])"
            return cell
        }else{ return collectionView.dequeueReusableCell(withReuseIdentifier: "PlaceholderCell", for: indexPath) }
    }
}

【问题讨论】:

  • 与您的问题无关,但无需使用if let cell...。只需强制投射出队的单元格。摆脱占位符单元格。不需要。

标签: ios swift uicollectionview uicollectionviewcell uistoryboard


【解决方案1】:

这个组合

private var newsCategories = ["Buisness","Sports","Health","Science","Entertainment","Technology","General","Everything"]

还有

UIImage(contentsOfFile: newsCategories[indexPath.item])

contentsOfFile 不正确,您需要参考下载图像的完整文件路径

使用

UIImage(named:newsCategories[indexPath.item])

如果图像是在应用程序主包中提供的

【讨论】:

  • 这个工作=>> cell.imageView.image = UIImage(named: newsCategories[indexPath.item], in: nil, compatibleWith: nil)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2012-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
  • 2022-01-11
相关资源
最近更新 更多