【发布时间】:2020-05-25 20:52:55
【问题描述】:
我很难根据 FB 实时数据库中的项目子节点来显示/隐藏我的 collectionview 单元格。该问题由三部分组成:FB 数据库、一个collectionview 和一个分段控件。我的目标是在 collectionview 中显示不同的单元格,具体取决于项目是否具有具有特定字符串值的子项。
我的数据库如下所示:
Items
category1
item1
name: item1
imageUrl: item1Url
logic
one
three
item2
name: item1
imageUrl: item1Url
logic
two
three
category2
item1
name: item1
imageUrl: item1Url
logic
two
four
item2
name: item1
imageUrl: item1Url
logic
one
two
我还有一个自定义 Product 类来在他们的单元格中显示我的项目:
class Product {
var category: String?
var name: String?
var imageUrl: String?
init(rawData: [String: AnyObject]) {
name = rawData["name"] as? String
imageUrl = rawData["imageUrl"] as? String
category = rawData["category"] as? String
}
}
我使用这个功能从 firebase 数据库加载我的项目:
func loadCategoryName() {
ref = Database.database().reference().child("Items").child(selectedCategoryFromPreviousVC)
ref.observeSingleEvent(of: .value) { (snapshot) in
if let data = snapshot.value as? [String: AnyObject] {
self.itemArray = []
let rawValues = Array(data.values)
for item in rawValues {
let product = Product(rawData: item as! [String: AnyObject])
product.category = self.selectedCategoryFromPreviousVC
self.itemArray.append(product)
}
// Sort item array by rating; if rating is same, sort by name
self.itemArray.sort { (s1, s2) -> Bool in
if s1.rating == s2.rating {
return s1.name! < s2.name!
} else {
return s1.rating > s2.rating
}
}
self.collectionView?.reloadData()
}
}
}
我的 itemArray 现在包含我的所有商品作为自定义产品,我可以在它们的单元格中显示它们。
我的分段控件:
func someFunc() {
let segmentController = UISegmentedControl(items: ["one", "two", "three", "four"])
segmentController.selectedSegmentIndex = 0
self.navigationItem.titleView = segmentController
segmentController.addTarget(self, action: #selector(handleSegment), for: .valueChanged)
}
@objc fileprivate func handleSegment() {
print(segmentController.selectedSegmentIndex)
}
使用 handleSegment 函数,我可以打印出已选择的段。但这就是问题发生的地方。我尝试创建新数组来拆分项目,以便项目根据它们的“逻辑”子节点位于一个数组中。但是我无法制作 Product 类型的数组,以便我可以使用它们来重新填充 collectionview。此外,我不确定在我的数据库中存储逻辑部分的最佳方式是什么。
【问题讨论】:
标签: ios swift firebase-realtime-database uicollectionview uisegmentedcontrol