Search code examples
iosswiftuicollectionviewswift4uicollectionviewdelegate

cellForItemAt function not getting called at UICollectionViewController in Swift 4


It seems pretty basic but I can't make it work in Swift 4.

So I have the following implementation of UICollectionViewController

class TestController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(MyCell.self, forCellWithReuseIdentifier: "default")
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath)
    }

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


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: view.frame.width, height: 100)
    }
}

Although ... numberOfItems ... method is being called, the one for ... cellForItemAt indexPath ... is not.

What am I missing?

This is the code for the cell

class MyCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .green
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Also, I'm not using storyboards so I'm instantiating this controller as follows in AppDelegate class:

...
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        window = UIWindow()
        window?.makeKeyAndVisible()

        window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))

        return true
    }
...

Solution

  • Instead of

    window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))
    

    in didFinishLaunchingWithOptions method use this

     window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: UICollectionViewFlowLayout()))