【发布时间】:2017-05-31 03:35:46
【问题描述】:
我正在尝试填充 Square 对象的二维数组 (UICollectionView):
class Square: NSObject {
var sqrKey: String!
var userId: String!
init(SqrNumber: String, UserID: String) {
self._sqrKey = SqrNumber
self._userId = UserID
}
}
ViewController 是这样的:
class CustomCollectionViewController: UICollectionViewController {
var ref: DatabaseReference!
var squares = [Square]()
override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference(withPath: "PlayerBoxes")
handle = ref.child("11062").observe(.value, with: { snapshot in
var items: [Square] = []
for item in snapshot.children {
let square = Square(snapshot: item as! DataSnapshot)
items.append(square)
}
self.squares = items
self.collectionView?.reloadData()
})
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
// Configure the cell
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CustomCollectionViewCell
cell.square = squares[(indexPath as NSIndexPath).item]
cell.label.text = cell.square?._sqrKey
return cell
}
}
我遇到了两个问题/错误:
第一个问题比错误还多,即在执行 collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 函数之前未完全完成 Firebase 读取,这会导致问题 fatal error: Index out of range
在线:cell.square = squares[(indexPath as NSIndexPath).item]
我该如何解决这个问题!?如何在继续之前强制 Firebase 读取完成!?
我的问题的第二部分是这个,我放置了虚拟数据以确保不会遇到上述错误/问题(通过硬编码 Square 对象数组)这确保不会遇到致命错误,并且我可以测试我的其余代码;但是当我这样做时,执行cell.label.text = cell.square?._sqrKey 时的结果输出我会为 UICollection 的每个部分中的每个项目获得相同的值!?
所以输出是:
0,1,2,3,4
0,1,2,3,4
0,1,2,3,4
0,1,2,3,4
0,1,2,3,4
我希望输出是
0,1,2,3,4,
5,6,7,8,9,
10,11,12,13,14
15,16,17,18,19
20,21,22,23,24
谁能帮我理解如何索引正确的_sqrKey 值!?
硬编码的 Square 对象是键值加 1,因此结果如上。
【问题讨论】:
标签: arrays swift uicollectionview