Mhmd Backer Shehadi Mhmd Backer Shehadi - 3 years ago 237
Swift Question

UICollectionView method (collectionView cellForItemAt indexPath ) not called

I am trying to make a custom bar menu using

,the problem is that cells not showed method
collectionView cellForItemAt indexPath
not called.

My code so far:

import UIKit
private let reuseIdentifier = "Cell"

class MenuBar : UIView ,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

lazy var collectionView : UICollectionView = {
let layout = UICollectionViewLayout()
let cv = UICollectionView(frame: .zero , collectionViewLayout : layout)
cv.dataSource = self
cv.delegate = self
cv.backgroundColor = UIColor.white
return cv

override init(frame: CGRect) {
super.init(frame: frame)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

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

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

return cell

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: frame.height/2, height: frame.height)

fileprivate func setUpCollectionViewConstraints() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["cv" : collectionView])
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat:"V:|[cv]|", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: ["cv" : collectionView])
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

Answer Source

Please check :

Your layout should be like below.

You used UICollectionViewLayout.

You have to use UICollectionViewFlowLayout

let layout = UICollectionViewFlowLayout()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download