Reputation: 31
Can somebody help? The function fetchUser()
is working and I see the users being loaded, but the cells of the collection view are not appearing. It's also programmatically.
The collection view is:
let newCollection: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
layout.scrollDirection = .horizontal
collection.backgroundColor = UIColor.green
collection.translatesAutoresizingMaskIntoConstraints = false
collection.isScrollEnabled = true
return collection
}()
and the collection view cells configured are:
extension WorkerUICollection: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return worker.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CustomeCell
let cellUsers = worker[indexPath.item]
cell.textLabel.text! = cellUsers.workerName
//cell.workerLocation.text! = "2.0 km"
cell.backgroundColor = .white
cell.layer.cornerRadius = 5
cell.layer.shadowOpacity = 3
//cell.imageView.image = UIImage(named: "user")
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 150, height: 250)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
}
}
The fetchUser() function:
func fetchUser() {
Database.database().reference().child("Users").observe(DataEventType.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let worker = WorkerInfo()
worker.workerName = (dictionary["username"] as! String?)!
//user.profileImageURL = dictionary["profileImageURL"] as! String?
DispatchQueue.main.async(execute: {
self.newCollection.reloadData()
})
}
print(snapshot)
}, withCancel: nil)
}
Any ideas?
Upvotes: 0
Views: 53
Reputation: 111
because your self.worker.count = 0. In your fetchUser()
function you should to update your datasource (worker) whit new one from your database. Try something like this.
if let array = snapshot.value as? [String: AnyObject] {
var tempWorkersArray: [WorkerInfo] = []
for dict in array {
let worker = WorkerInfo()
worker.workerName = (dict["username"] as? String) ?? ""
tempWorkersArray.append(worker)
}
self.worker = tempWorkersArray
DispatchQueue.main.async {
self.newCollection.reloadData()
}
}
Upvotes: 1