ios - 尽管调试器中图像变量不为零,为什么 UICollectionViewCell 图像未加载?

标签 ios swift uicollectionview uicollectionviewcell uistoryboard

我正在使用 Collection View 来显示新闻应用程序中的类别选择。 我的收藏 View 图像未加载到单元格中。在检查调试器时,图像 var 包含该图像。 图像将从 Assets.xcassets 文件夹加载。 当在调试器中打印单元 View 图像的值时,它显示 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) }
    }
}

最佳答案

这个组合

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

UIImage(contentsOfFile: newsCategories[indexPath.item])

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

或者使用

UIImage(named:newsCategories[indexPath.item])

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

关于ios - 尽管调试器中图像变量不为零,为什么 UICollectionViewCell 图像未加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56673364/

相关文章:

ios - 如何在 map 中标记注释并在选择注释时获取标记值

swift - 在 Scenekit 中计算到达角度

ios - UISwitch 的 UICollectionview 点击事件

Swift 等效于 java 返回类型 : Class<? extends MyClass<?>>

ios - 适用于 iOS 的 GCM,永远不会调用 gcm 连接处理程序

iOS 11 导航 TitleView 错位

iphone - 一起使用 UINavigationController 和标签栏

ios - 从 AppDelegate 呈现一个 ViewController

ios - 基于屏幕尺寸的 UI 元素间距

ios - 如何将数据从collectionView和tableView传递到detailViewController?