Reputation: 407
I'm designing the UI of an ios 8 app being built in swift. I have intermediate knowledge of autolayout and constraints. Here's my situation: I have a custom collection view controller and collection view cell. I want to use the "equal widths" and "equal heights" constraints within interface builder to set the width and height of a cell relative to a multiplier of the parent view-- as opposed to using intrinsic height/width properties such as 320 x 94.
Here's what I tried
Should I just settle for the intrinsic height and width and assume that CollectionViewFlowLayout will take care of me or is there a way to do this programatically?
Thanks. Alex
Upvotes: 8
Views: 2531
Reputation: 1814
Layout and size of cells is done by the collectionViewLayout property of collectionView. Using a collectionViewLayout of class UICollectionViewFlowLayout, you can set fixed size using item size property:
(collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize = 100 //set fixed size here
or set variable size using delegate method:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// determine variable size here using indexPath value
}
Upvotes: 0
Reputation: 17372
Use the UICollectionViewDelegateFlowLayout
methods to tune your cell size
for example if you want 3 cells across the view width
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 tune the distance between the cells with
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat
and the edge insets with
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
Upvotes: 0