我正在使用 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/