我有这个firebase数据库结构:
Main
----- Name 1
--------value 1
--------value 2
--------value 3
----- Name 2
--------value 1
--------value 1
--------value 1
我试图获取所有键值并存储到自定义类的数组中。
我的自定义类有一个init:
init(name: String, photo: String) {
self._name = name
self._photo = photo
}
所以在我的View控制器中我有:
var array = [customClass]()
let ref = Database.database().reference().child("Main")
func getInfo(){
Ref.observeSingleEvent(of: .value) { (snapshot) in
var arrayTemp = [customClass]()
for child in snapshot.children {
let snap = child as! DataSnapshot
let name = snap.key
let custom = customClass(Name: name, photo: "")
arrayTemp.append(custom)
}
self.array = arrayTemp
self.collectionView.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? Cell {
let custom: Custom!
custom = array[indexPath.row]
cell.configureCell(custom)
return cell
} else {
return UICollectionViewCell()
}
}
这是单元格:
class Cell: UICollectionViewCell {
@IBOutlet weak var Thumb: UIImageView!
@IBOutlet weak var NameLbl: UILabel!
var custom: CustomClass!
func configureCell(_ custom: customClass) {
self.custom = custom
NameLbl.text = self.custom.customName.capitalized
var url = URL(string: self.custom.photoUrl)
if url == nil {
url = URL(string: "")
}
Thumb.sd_setImage(with: url)
}
}
我的问题是,如果我打印名称我拥有Db中的所有值,但是当我重新加载集合视图时,我看到项目的数量正确,但名称只是重复x时间的第一个元素... 有什么帮助吗?
答案 0 :(得分:1)
解决问题:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.array.count
}