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

0ndre_ picture 0ndre_ · Oct 13, 2016 · Viewed 50.9k times · Source

I have a tableView and in every tableViewCell is a collectionView.

I am trying to change the collectionView size with this code:

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

    if collectionView.tag == 2{

        return CGSize(width: 100, height: 100)

    }else if collectionView.tag == 4 {


        return CGSize(width: 222, height: 200)

    }else{


        return CGSize(width: 10, height: 10)
    }

}

The problem is that there is no error but cells do not change sizes

If you need to know something more, just write a comment.

Thank you.

Answer

Burak Dizlek picture Burak Dizlek · Nov 7, 2019

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