Set collectionView size. (sizeForItemAtIndexPath function is not working) Swift 3

First, don't forget extends from UICollectionViewDelegateFlowLayout delegate.

For single collectionview display logic :

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = ((collectionView.frame.width - 15) / 2) // 15 because of paddings
    print("cell width : \(width)")
    return CGSize(width: width, height: 200)
}

And important point in storyboard don't forget Estimate Size : None

estimate_size_none


The signature for this method has changed in Swift 3 to:

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    // your code here
}

Pay attention to the subtle difference: (_ collectionView: ... instead of (collectionView: ....

This is because in Swift 3, you have to explicitly specify the label of the first parameter. You can override this default behaviour by adding the underscore character _.

Also, make sure that your class adopts both UICollectionViewDelegate and UICollectionViewDelegateFlowLayout protocols

class MyViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    // your code here

    func collectionView(_ collectionView: UICollectionView,
                layout collectionViewLayout: UICollectionViewLayout,
                sizeForItemAt indexPath: IndexPath) -> CGSize {
        // your code here
    }
}

Refer to this link to learn more about changes in Swift 3.


You need to specify that you implement the protocol UICollectionViewDelegateFlowLayout in your class declaration.

class PhrasesCompactCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout