iosuicollectionviewuicollectionviewcellpagedcollectionview

How to pin the edges of a CollectionViewCell to the CollectionView when using PagedView


I'm using AutoLayout and have a collectionView that has Paging Enabled. I want each CollectionViewCell to be exactly the width & height of it's CollectionView Container. However, on AutoLayout when I select the CollectionViewCell and try to pin it's edges to the parent (CollectionView) those options are greyed out.enter image description here

I've set the cell size here, but really I want the cell's width and height to grow/shrink according to the size of the collectionView. The CollectionView has autolayout constraints applied to it. enter image description here

The Arrange > Position View > Fill Container looked like it might be what I am looking for, but those options were greyed out too. enter image description here


Solution

  • The reason why the options for pinning the edges of a collection view cell to the edges of the collection view itself are grayed out is that if you did that you wouldn't be able to scroll in any direction. If you could constrain a cell's leading edge to be equal to the collection view's leading edge, and you did the same with the corresponding trailing, top and bottom edges there wouldn't be any more space for a second or a third cell... right?

    So the way you wanna go is to implement a flow layout and make use of its collectionView:layout:sizeForItemAtIndexPath: method. Inside this method you can dynamically calculate your cell's size and return the appropriate value. If all your cells should be of equal size it gets easier and you can simply set the flow layout's itemSize property.