UICollectionView 3 column grid, 1px space?? (image included)

Alex picture Alex · Apr 4, 2015 · Viewed 8.6k times · Source

I have setup a UICollectionView with a FlowLayout that leaves no space in between cells in either the vertical or horizontal directions.

I have everything working, yet there is an odd 1px space between the 2nd and 3rd column and I have no idea why!? I have verified the 1px gap shows up both in iOS simulator and on a real device. Has anybody experienced this?

My UIViewController is a delegate/datasource of the following:

class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

I have implemented the necessary functions to remove any spacing (and verified with print statements that they are running), as well as visual confirmation of the cells lining up next to each other:

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

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

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

Finally, I have printed out the width of the cell being returned (each color square) to verify it was the (view.frame.width / 3) or (320/3), which is 106.666667

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

    var totalHeight: CGFloat = (self.view.frame.width / 3)
    var totalWidth: CGFloat = (self.view.frame.width / 3)

    println(totalWidth) // this prints 106.666666667

    return CGSizeMake(totalWidth, totalHeight)
}

enter image description here

Answer

dimpiax picture dimpiax · Apr 4, 2015

Better avoid number's double type in similar situations. Use:

return CGSizeMake(ceil(totalWidth), ceil(totalHeight))