Nikhil Chandra
Nikhil Chandra

Reputation: 163

Cells of UICollectionsView in Xcode Not Appearing

I am developing an app and set up a UICollectionView. Below is the code for the view controller for where the UICollectionView is located in:

import UIKit
import Firebase
import FirebaseFirestoreSwift
import FirebaseFirestore

class scrollCollectionViewController: UICollectionViewController{
    var tournaments = [String]()
    @IBOutlet weak var collectionview: UICollectionView!
    override func viewDidLoad() {
        fetchTourneys()
        super.viewDidLoad()
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        

        // Do any additional setup after loading the view.
    }
    
    func fetchTourneys() {
       let db = Firestore.firestore()
       db.collection("Tournaments").getDocuments() { (querySnapshot, err) in
               if let err = err {
                   print("Error getting documents: \(err)")
               } else {
                   for document in querySnapshot!.documents {
                       print("\(document.documentID) => \(document.data())")
                       self.tournaments.append(document.documentID)
                   }
               }
       }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
       return self.tournaments.count
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
       return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tourneyIdentifier", for: indexPath) as! ScrollCollectionViewCell
       cell.tournamentTitle.text = tournaments[indexPath.row]
       print(cell.tournamentTitle.text)
    // Configure the cell

       return cell
    }

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return false
    }

    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return false
    }

    override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
    
    }
    */
}

The cells just dont end up showing up. After including some print statements, I noticed none of the override funcs for numberOfSections or the collection views seem to be running. What could be the issue for why these are not running, and why the cells are not showing up?

Upvotes: 0

Views: 136

Answers (5)

Nikhil Chandra
Nikhil Chandra

Reputation: 163

Everyone's answers pointed out errors in the code which moved it in the right direction. But it still did not end up showing the cells. I printed each cell, and noticed that there was a parameter that made them all hidden. I have no idea what caused that. But I added the following code:

    cell.isHidden = false

And it worked out great!

Upvotes: 0

Marcus Ziadé
Marcus Ziadé

Reputation: 880

You need to set collectionview datasource and delegate to self in viewDidLoad

put delegate = self and dataSource = self in viewDidLoad

Upvotes: 1

Frankenstein
Frankenstein

Reputation: 16341

You have to call reloadData on collectionview once the fetchTourneys is complete.

func fetchTourneys() {
    let db = Firestore.firestore()
    db.collection("Tournaments").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                self.tournaments.append(document.documentID)
            }
            self.collectionview.reloadData()
        }
    }
}

Upvotes: 1

Jay
Jay

Reputation: 35657

Please move the fetchTourneys() after super.viewDidLoad(). Also, you need to ensure the cell identifier is set up correctly and registered with your collectionView

private let reuseIdentifier = "tourneyIdentifier"

class scrollCollectionViewController: UICollectionViewController {
    var tournaments = [String]()

    @IBOutlet weak var collectionview: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Register cell classes
        self.collectionview!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        fetchTourneys()
    }

then, when the cells are being created, re-use the reuseIdentifier

.dequeueReusableCell(withReuseIdentifier: reuseIdentifier

Also, within your Firebase function, ensure you tell the collectionView to update after you've populated the dataSource

if let err = err {
    print("Error getting documents: \(err)")
} else {
    for document in querySnapshot!.documents {
        print("\(document.documentID) => \(document.data())")
        self.tournaments.append(document.documentID)
    }
    self.collectionview.reloadData()
}

Also you said

I noticed none of the override funcs for numberOfSections or the collection views seem to be running

That would indicate your UICollectionView doesn't know this code is it's viewController. Ensure you've set that up in XCode Inspector. Generally speaking, Classes and Structs should start with a capital letter, vars are lowercased

enter image description here

Upvotes: 1

Jawad Ali
Jawad Ali

Reputation: 14397

you need to return self.tournaments.count in numberOfItemsInSection

func fetchTourneys() {
    let db = Firestore.firestore()
    db.collection("Tournaments").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                self.tournaments.append(document.documentID)
            }
            
                self.collectionview.reloadData()
            
        }
    }
}



override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
           return 1
       }


       override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
           return self.tournaments.count
       }

Upvotes: 1

Related Questions