Delegate Methods Never Called

Hi Apple Dev Community,

I’ve searched both here and google for similar questions, but none of the answers I found actually helped me…

So bacically, I am trying to add subviews (in my case UICollectionView) programmatically, but when I do so, the delegate methods never get called.

Here is the code:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    var collectionView: UICollectionView!

    override func viewDidLoad() {
        let myLayout = UICollectionViewFlowLayout()
        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: myLayout)
        collectionView.backgroundColor =
        collectionView.delegate = self
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)
        -> Int {
            return 50
    // Initialize each cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
        -> UICollectionViewCell {
            let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath
                as IndexPath) as! CollectionViewCell
            myCell.backgroundColor =
            return myCell

As you can see, viewDidLoad is successfully called, but the deledate methods are never called.

Please notice how I explicitly set

collectionView.delegate = self


However, even that is not enough to get the delegate methods to fire. Clearly, I must be missing something.

Does anyone know how I can fix this code?

Thanks in advance!

Powered by WPeMatico

You may also like...

Comments are closed.