-1

The collectionView shows cells without any problem except the spacing, some spacing are not equal to others, they are a little bit bigger than others. Even I set margin = 0, some spacing still comes out.

Here is the code:

let margin = 1
let cellSize = (size.width-margin*(cellsPerRow+1)) / cellsPerRow
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
layout.itemSize = CGSize(width: cellSize, height: cellSize)
layout.minimumInteritemSpacing = margin
layout.minimumLineSpacing = margin

enter image description here

Thanks.

jdleung
  • 1,088
  • 2
  • 10
  • 26
  • You are performing a division: `let cellSize = (size.width-margin*(cellsPerRow+1)) / cellsPerRow`. What should happen if the division doesn't go evenly? You can't have a nonintegral number of points. – matt Oct 02 '17 at 23:54
  • I looks like your arithmetic is wrong, you need to adjust you brackets. let cellSize = ((size.width-margin)*(cellsPerRow+1)) / cellsPerRow – arvidurs Oct 03 '17 at 00:12
  • @matt cellsPerRow is converted to CGFloat before operation. – jdleung Oct 03 '17 at 00:40
  • @arvidurs it's totally wrong size ;-( – jdleung Oct 03 '17 at 00:41

1 Answers1

1

You need to define the cell size based on maximum (integer) width/height that fits your whole area, then take the "leftover" (=area_width_or_height - (cell_size*cell_amount) ) and divide it by two to get the size of margins you need to leave to left/right/top/bottom to make the grid even. Now you get your cells slightly random based on whether you round to lower or higher number.