首页 > 解决方案 > 如何将我的 Firebase 数据从 didSelectItemAt 最终传递给 cellForRowAt(无情节提要)

问题描述

我能够从数据库中提取我自己的数据并将其显示到我的 collectionViewCells... 这是我的CustomCell ( UICollectionViewCell ) 上的标签,用于引用我的 Category 模型(我在这里只添加了一个标签来简化我我在问:))

func generateCell(_ category: Category) {

    nameLabel.text = category.name

}

这就是我的主要 UICollectionViewController

///empty array to collect data
var categoryArray: [Category] = []

//

private func loadCategories() {
    downloadCategoriesFromFireBase { (allCategories) in
        //            print("we have \(allCategories.count)")
        self.categoryArray = allCategories
        self.collectionView.reloadData()
    }
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadCategories()
}

//CellForItemAt

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCell

    cell.generateCell(categoryArray[indexPath.row])

    return cell
}

这就像一个魅力,并用所有数据正确显示我的所有单元格。

问题didSelectItemAt在于此

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let category = categoryArray[indexPath.item]

    let newVC = SomeTableViewController()

    newVC.category?.name = category.name

     navigationController?.pushViewController(newVC, animated: true)

}

根据您在 didSelectItemAt 上看到的内容,并且在我将其var category: Category?放在 SomeTableViewController() 上后,nil当我尝试在 viewDidLoad() 上打印类别名称时,类别类型仍会返回

How can I pass my category info to the tableViewController after I've selected a certain cell without Storyboard?

标签: iosswiftfirebaseswift5

解决方案


You need to pass the entire category object instead of passing the property name to the non initialized newVC category object (which is why your newVC category object is equal to nil).

So, essentially, instead of this:

newVC.category?.name = category.name

Do this:

newVC.category = category

An optional chain (in your case category?.name) will only succeed, if the optionals inside that chain contain a value. In your case, category is still nil since it wasn't assigned a value at the time you were trying to assign a name to it.

To illustrate what you are doing with an example:

var category: Category! /* category is nil since it's not initialized */
category?.name = name  /* category is still nil, so assigning a value to its property fails */

推荐阅读