dan10
dan10

Reputation: 119

Adaptive UICollectionView Cell Width

I am new to collection view and Auto Layout and I have a problem making the cell sizes adapt to the various devices in the simulator. I am using the flow-layout and I set the sizes in the size inspector. The image I've provided shows the way I need the cells to look(canvas on the left iPhone5)on all devices. The iPhone4 display is good but the 6s is incorrect. Can someone please show me how this is done as I cannot find the precise information I am looking for. Thanks

Also, I'm not sure why the iPhone5 doesn't display the cells on the preview section like the 4&6 do..? any clues..?

screen shot1

Upvotes: 0

Views: 1545

Answers (1)

Mike Taverne
Mike Taverne

Reputation: 9352

With UICollectionView, you need to calculate the size of your cells, and the space around them (insets and interitem spacing) using delegate methods.

Something like this should work for you:

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

    return UIEdgeInsets(top: 8, left: 4, bottom: 0, right: 4)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return CGFloat(8)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let cellWidth = (view.bounds.size.width - 16) / 2
    let cellHeight = cellWidth * 0.8 // multiply by some factor to make cell rectangular not square

    return CGSize(width: cellWidth, height: cellHeight)
}

Within a UICollectionViewCell is where you would use Auto Layout to position the things in the cell, like labels, images, etc.

iPhone 5s

iPhone 6s Plus

Upvotes: 4

Related Questions