ios - 如何将我的 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?
解决方案
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 */
推荐阅读
- python - 将 Flask 与子域一起使用会破坏 Google 任务队列路由
- python - “elif”语句不起作用并引发错误 - python
- azure - 在 Azure 门户下部署网站有多少种不同的方式?
- c# - TreeView 检测节点选择,但在选中或取消选中时不检测
- c++ - if 函数的另一种解决方案,减少写作
- r - 根据列表位置绑定列表列表
- amazon-web-services - S3 lambda 上传问题:管道损坏
- javascript - 在 JavaScript 中使用 fetch 通过 Twitter API 的 Auth1.0a
- reactjs - Spring Boot Rest Controller POST 请求总是使用@SessionScope 创建新的 sessionid?
- python - 如果多个元素具有相同的优先级,python中是否存在“Lifo”类型的优先级队列?