Josh Kahane
Josh Kahane

Reputation: 17169

UICollectionViewCell Auto Size?

Example, we have a UICollectionView with full width of the screen. This has 3 100 x 100px cells. On my iPad it will spread these across the full width leaving large gaps between each cell, naturally smaller gaps on a device with a smaller screen, i.e. an iPhone.

Is it possible to have the cell width automatically change depending on screen width to eliminate these gaps? I only want the expected, as set, 5px spacing.

Upvotes: 0

Views: 1608

Answers (1)

Zaid Pathan
Zaid Pathan

Reputation: 16820

Step 1: Implement UICollectionViewDelegateFlowLayout

Step 2: Use delegate method of UICollectionViewDelegateFlowLayout.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    return CGSizeMake((UIScreen.mainScreen().bounds.width-10)/3,120); //use height whatever you wants.
}

Step 3: Go to XIB or StoryBoard where you have your CollectionView.

Step 4: In XIB or StoryBoard where you have your CollectionView click on CollectionView.

Step 5: Go to InterfaceBuilder, then in second last tab (ie: Size Inspector) set Min Spacing

For Cells = 5

For Lines = 5

That it.

Upvotes: 3

Related Questions