Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set spacing between columns in a UICollectionView with a vertical scrolling grid

I'm kinda new to UICollectionViewFlowLayout sophisticated topics, and yes!! I have checked all topic-related questions but still I'm stuck.

All I'm trying to achieve is to set spacing between columns in UICollectionView with a vertical grid layout. And from all previous questions on the "how to set spacing on UIcollectionViewCells" topic, the primary answers that I have try'd unsuccessfully Are:

  1. using minimumInteritemSpacing and minimumLineSpacing

  2. using func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

the second solution for some reason did not achieve my goal and the first solution is unhelpful in a vertical grid layout as the apple Docs instruct on the collectionView(_:layout:minimumLineSpacingForSectionAt:):

For a vertically scrolling grid, this value represents the minimum spacing between successive rows. For a horizontally scrolling grid, this value represents the minimum spacing between successive columns

my question is: How could I do an easy workaround so that I could set spacing between columns in a vertical collectionView , since the exiting minimumInteritemSpacing and minimumLineSpacing apply on columns only on a horizontal grid.

like image 610
Hudi Ilfeld Avatar asked Sep 19 '25 11:09

Hudi Ilfeld


1 Answers

The spacing between cells (columns) is determined by the width of the collectionView and the width of the cells and the "Minimum Spacing for Cells".

So, if your collectionView is 300-pts wide, and your cells are 100-pts wide, 3 cells * 100 == 300.

If your min-spacing is Zero, you will get 3 cells on each row with Zero spacing.

If you set min-spacing to 40, 3 cells * 100 + (2 spaces * 40) == 380... which is too wide, so you will get only 2 cells on each row, and the space between will be 300 - (100 * 2) == 100.

So, to get a specific, fixed space between cells (columns), you need to calculate the total width needed and either change the width or the Section Insets of your collectionView.

like image 69
DonMag Avatar answered Sep 22 '25 04:09

DonMag