chl chl - 4 months ago 14
Swift Question

Auto Layout size of CollectionViewCell in relation to CollectionView

I have a CollectionViewCell placed in a CollectionView. The size of the CollectionView is set via Auto Layout and can change at times.

I want to (programmatically) set constraints on my CollectionView, so that the size of the CollectionViewCell is responsive to the size of the CollectionView (Say the width of the Cell is equal to the width of the CollectionView-100 and the height should be equal).

How can I declare constraints between the Cell and the CollectionView?

When, where and how do set those constraints? Do I have to call setNeedsLayout on the Cells when the size of the CollectionView changes?

I searched for this quite long and all I found was always about changing the size of the Cell according to its content – that’s not what I am trying to do. The only hint that I got is that I might have to subclass CollectionViewLayout – but I’m not sure about that.

Any help is appreciated!

Answer

You cant achieve this by using constrains but you can easily do that by using UICollectionViewDelegate sizeForItemAtIndexPath method. Example :

func collectionView(collectionView: UICollectionView,
                  layout collectionViewLayout: UICollectionViewLayout,
  sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

    return CGSizeMake(collectionView.frame.size.width / 2 ,collectionView.frame.size.height/ 2)
}

And after changing collectionView size all you need to do is calling its reloadData method

Comments