Recommendations for setting auto-width and height limits for a collection view cell?

I am developing a user interface for ios 8 application created in quick mode. I have intermediate knowledge about auto detection and limitations. Here is my situation: I have a custom collection view controller and collection. I want to use "equal width" and "equal height" constraints in the interface builder to set the width and height of the cell relative to the multiplier of the parent view - as opposed to using my own height and width properties, such as 320 x 94.

Here is what I tried

  • using the inner width and height for dimension classes inside IB. (This does not work)
  • Drag and drop control from UICollectionViewCell to CollectionView (not working as "equal heights" and "equal width" are not even constraint parameters)

Should I just rely on the inner height and width and assume that CollectionViewFlowLayout will take care of me, or is there a way to do this programmatically?

Thanks. Alex

+7
ios autolayout swift uicollectionview uicollectionviewcell
source share
2 answers

Layout and cell size are performed by the collectionViewLayout property of the collectionView. Using the collectionViewLayout of the UICollectionViewFlowLayout class, you can set a fixed size using the element size property:

(collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize = 100 //set fixed size here 

or set the size of the variable using the delegation method:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // determine variable size here using indexPath value } 
0
source share

Use the UICollectionViewDelegateFlowLayout methods to adjust the size of your cell

for example, if you want 3 cells in the width of the view

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let width = CGRectGetWidth(collectionView.bounds) let hcount = 3 let gapcount = CGFloat(hcount) + 1 //this should be a class var/constant which you can feed into the minimumLineSpacingForSectionAtIndex delegate let gap = 10 let kwidth = width - gap let keywidth = kwidth/CGFloat(hcount) return CGSize(width:keywidth,height:50) } 

You can adjust the distance between cells with

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat

and edge inserts with

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets

-one
source share

All Articles