Search code examples
iosswiftxcodeuicollectionviewuicollectionviewlayout

Controlling the gap between cells in UICollectionViewController


My cells seem to have a gap of about 20 points, I want to control that value, but every answer I found regarding this question does not work.

I tried:

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

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

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets.zero
}

without any useful output, also:

layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0

and these two lines also didn't help.

Please note that I'm not using the storyboard!


Solution

  • Logically speaking, the gap value should be based on what's the cell size, editing the minimum spaces leads to how the row should be displayed. To make it more clear, consider the following scenario:

    it's required to display 2 cells for each row, each cell's width should be half of the screen width, if the minimum spaces have been set to zeros, the output will be: both cells should fill the screen width.

    So far so good, but what if the cell's width should be more than half of the screen width (let's consider that it should be half of the width + 2 points)? the output will be: each row will contain only 1 cell, besides it a gap with the width of the half of screen - 2 points.

    So, the solution is to make sure to set the appropriate size for the cells, by implementing collection​View:​layout:​size​For​Item​At​Index​Path:​ correctly. You might want to check this Q&A to know how you can achieve it.