iosswiftuicollectionviewdelegatesuicollectionviewdelegateflowlayout

Why does the UICollectionView's delegate methods don't work?


I created a collectionView and I made it's delegate conform to UICollectionViewDelegateFlowLayout protocol attached to the main ViewController in order to modify some aspects of the UICollectionView's cells. Initially I did this:

override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView.delegate = self 

}

then I realised that this didn't work since there was an error, so I fixed it doing this:

 override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView.delegate = self as? UICollectionViewDelegateFlowLayout

}

The problem is that every method I try to implement in the ViewController doesn't seem to work during runtime.

f.e. I implemented this method here:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: collectionView.frame.width/3, height: collectionView.frame.width/3)

}

but it doesn't work during the run of the application.


Solution

  • "so I fixed it doing this"

    You made the error go away, but you didn't fix it. You need to make your view controller class actually adopt UICollectionViewDelegateFlowLayout by either adding it to its class declaration like this:

    class ProfileViewController: UIViewController, UICollectionViewDelegateFlowLayout {
    

    or by adding it to an extension of your view controller, like this:

    extension ProfileViewController: UICollectionViewDelegateFlowLayout {