为什么在调试器中image var不是nil,为什么UICollectionViewCell图像没有加载?

时间:2019-06-19 17:52:33

标签: ios swift uicollectionview uicollectionviewcell uistoryboard

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

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) }
    }
}

2 个答案:

答案 0 :(得分:0)

此组合

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

还有

UIImage(contentsOfFile: newsCategories[indexPath.item])

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

使用

UIImage(named:newsCategories[indexPath.item])

如果图像包含在应用程序主捆绑包中

答案 1 :(得分:-2)

UIImage(contentsOfFile:)-从项目包中返回UIImage,从您作为参数传递的特定路径返回。

UIImage(named :)-返回UIImage,但它正在查找文件,其中包含您在Assets.xcassets项目目录中作为参数传递的“名称”