Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 935
chl Avatar asked Mar 16 '23 16:03

chl


1 Answers

You cannot achieve this using constraints, but you can easily do this using UICollectionViewDelegate's sizeForItemAtIndexPath method. Example:

func collectionView(collectionView: UICollectionView, 
       layout collectionViewLayout: UICollectionViewLayout,
  sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.size.width / 2, height: collectionView.frame.size.height/ 2)
}

And after changing the collectionView size all you need to do is call its reloadData method.

like image 164
Zell B. Avatar answered Mar 23 '23 01:03

Zell B.