如何将我的 Firebase 数据从 didSelectItemAt 传递到最终的 cellForRowAt(w/o 故事板)

How to pass my Firebase data from didSelectItemAt to ultimately cellForRowAt (w/o storyboard)

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

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() 上后,当我尝试打印类别名称时,类别类型仍然是 return nil在我的 viewDidLoad()

在没有 Storyboard 的情况下选择了某个单元格后,如何将我的类别信息传递给 tableViewController?

您需要传递整个类别对象,而不是将 属性 名称传递给未初始化的 newVC 类别对象(这就是为什么您的 newVC 类别对象等于 nil)。

所以,基本上,而不是这个:

newVC.category?.name = category.name

这样做:

newVC.category = category

可选链(在您的例子中是 category?.name)只有在该链中的可选值包含值时才会成功。在您的情况下,类别仍然为零,因为在您尝试为其分配名称时未为其分配值。

用一个例子来说明你在做什么:

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 */