UICollectionView cellForItem not being called
I am implementing UICollectionView (collectionView) in base ViewController my collection view needs to fetch 5 cells as in codeofItemInSection. The CollectionView is displayed and the numofItemInSection function is called, but the 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
}
}
+3
source to share
2 answers
This is your collectionView height or collectionView frame, then you need to set the correct height in collectionView.
OR
Try
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
}
0
source to share