4

I am implementing a UICollectionView (collectionView) in a basic ViewController my collection view must retrieve 5 cells as in numbersofItemInSection code. CollectionView is showed and numbersofItemInSection function is called but cellForItemAt function is not called so the collection view is empty.

import UIKit


private let reuseIdentifier = "Cell"



class TestViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{

    lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.delegate = self
        cv.dataSource = self
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        collectionView.backgroundColor = .white
        navigationItem.title = "test"

        setupViews()
    }

    func setupViews(){
        view.addSubview(collectionView)

        collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        collectionView.heightAnchor.constraint(equalToConstant: 60).isActive = true
        collectionView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
    }

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
        // Configure the cell

        cell.backgroundColor = .red

        return cell
    }


}
zorobabel
  • 98
  • 6

2 Answers2

0

It is your collectionView's height or collectionView's frame issue then you need set proper height to collectionView .

OR

Try this

     override func viewDidLoad() {
                super.viewDidLoad()
                navigationItem.title = "test"

                setupViews()
                collectionView.backgroundColor = .white
                self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) 
// remove this line if you not use xib

            }
KKRocks
  • 8,222
  • 1
  • 18
  • 84
0

I have checked your code and it is working fine.As u are using swift 3 so you will have to use xCode 8+.Run it with XCODE 8, as the syntax is for swift 3 and you will get the result.

Garima Saini
  • 173
  • 8