Reshan Kumarasingam Reshan Kumarasingam - 1 month ago 6
iOS Question

UICollectionView with zero cell spacing

I've followed this answer and try to implement 5 cells per row and it's working great when I check on iPhone 6 & iPhone SE as below.

But the problem occures when I try to run it on iPhone 6 Plus. Can anyone help me out on figuring out the issue please?

This is my code.

screenSize = UIScreen.main.bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
let itemWidth : CGFloat = (screenWidth / 5)

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 10.0, left: 0, bottom: 10.0, right: 0)
collectionView!.collectionViewLayout = layout

Answer

It has to be

let itemWidth : CGFloat = (screenWidth / 5.0)

So the result will not be rounded.

Updated

Please make sure if you use storyboard to create your UICollectionView, remember to set autolayout to the collection view's size so that it is updated to whatever current screen size is.

Update 2

If you use storyboard there is no need to create a UICollectionViewFlowLayout. You can set the insets and spacings from storyboard. Then in your .m file implement this to determine item's size.

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
     return yourDesiredSize;
}
Comments