【问题标题】:CoreData: How to display fetched data to UIcollectionView CellCoreData:如何将获取的数据显示到 UIcollectionView Cell
【发布时间】:2020-11-18 10:17:52
【问题描述】:

目前我有这个 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 { 
    ... 
}

非常感谢任何建议或任何更好的方法让它发挥作用!

【问题讨论】:

  • 您想将 charachterArray 的一个索引传递给单元格子类?

标签: ios swift core-data uicollectionviewcell nsfetchrequest


【解决方案1】:

你只需要获取indexPath.item对应的characterArray元素,并用它传递到单元格中。

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]

【讨论】:

  • 我使用 collectionViewCell 的原因是因为我还有其他与单元格有关的东西,例如图像、imageCatching...如果我将所有内容结合起来,那将是一团糟
  • 为您需要传递的所有数据创建一个模型,并使用它来将数据传递到单元格。检查更新,我添加了一个小例子。
  • 太棒了!我会试一下!!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 2020-09-14
  • 2019-09-08
  • 1970-01-01
相关资源
最近更新 更多