【发布时间】:2017-06-24 22:49:26
【问题描述】:
我有一个 collectionView,我正在获取 firebase 数据库数据。我的 collectionView 创建发送 firebase indexpath.row。这行 0 , 1, 2, 3, ... 但 firebase 响应不规则数据,我参见 debug mod indexpath.row 16 , 3, 7 , 11...
有什么问题?
我分享我的示例代码。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print(indexPath.row) // 1, 2, 3, 4
self.ref.child(userID!).child(self.islemString).child(String(indexPath.row + 1)).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let asd = value?["xxx"] as? Int ?? 0
print(indexPath.row) // 16, 3, 7 ,9
if(asd == 0) {
cell.imageKilit.image = UIImage(named: "kilit")
}
else{
cell.imageKilit.image = UIImage(named: "")
}
}
)
}
【问题讨论】:
-
您的代码第 3 行非常神秘。索引路径需要不同的时间,因此在闭包中您不会以相同的顺序获得它们。
-
我该如何解决?
-
不用解决。顺序应该是非关键的。
-
怎么样?你能举个例子吗?
-
这种方法不会长期有效。如果您的表中有 100 行,则代码将加载 Firebase 100 次,等待返回来填充集合中的每个单元格。最好一次将所有 100 个加载到一个数组中,然后让集合视图使用 reloadData() 进行自我更新。此外,滚动和其他活动确实会受到影响 - 再次,一次加载您想要的数据或一部分数据(10 行,然后是另外 10 行等)将是一个更好的方向。跨度>