首页 > 解决方案 > CoreData:如何将获取的数据显示到 UIcollectionView Cell

问题描述

目前我有这个loadCharacters函数

    var characterArray = [Character]()

    func loadCharacters(with request: NSFetchRequest<Character> = Character.fetchRequest()) {
        
        do {
            characterArray = try context.fetch(request)
        } catch {
            print("error loading data")
        }        
        collectionView.reloadData()
    }

我的问题是:如何将获取的数据从那里传递给我的子类CharacterCollectionViewCell,然后再将此单元格用于我的

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
 -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "characterCell",
 for: indexPath) as! CharacterCollectionViewCell { 
    ... 
}

非常感谢任何建议或任何更好的方法来使它起作用!

标签: iosswiftcore-datauicollectionviewcellnsfetchrequest

解决方案


您只需要获取characterArray对应的元素indexPath.item并使用它来将其传递到单元格中。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
 -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "characterCell",
 for: indexPath) as! CharacterCollectionViewCell { 
        cell.someLabel.text = characterArray[indexPath.item]
        //...
        return cell
}

如果要传递的数据太多,最好创建一个模型并使用它的实例将数据传递到单元格。因此,为此首先创建一个模型。

struct CharacterCellModel { // all properties... }

然后在你的UIViewController子类中。

var characterCellModels = [CharacterCellModel]() // append this model

最后在cellForItemAt

cell.characterCellModel = characterCellModels[indexPath.item]

推荐阅读