Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning collection view cells to fit exactly 3 per row

Tags:

I am trying to make a collection view of images, so that there are 3 per row, with no spacing in between.

My collection view data sources are:

func numberOfSections(in collectionView: UICollectionView) -> Int {     return 1 }  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {     return posts.count } 

and this is how it's set up in my storyboard (imageView width is 125, a third of the 375 screen width):

enter image description here

However when I run the app and add some photos, it looks like this:

enter image description here

How can I fix this so that I see 3 images per row? Thanks for any help!

like image 205
KingTim Avatar asked Mar 09 '17 15:03

KingTim


People also ask

How do I change the spacing between cells in collection view?

I have found very easy way to configure spacing between cells or rows by using IB. Just select UICollectionView from storyboard/Xib file and click in Size Inspector as specified in below image. For configuring space programatically use following properties. 1) For setting space between rows.

What is Uicollectionviewflowlayout?

A layout object that organizes items into a grid with optional header and footer views for each section.


1 Answers

You have to implement the

UICollectionViewDelegateFlowLayout

for the spacing stuff.

Set the size of the collectionViewCells like this:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {     let yourWidth = collectionView.bounds.width/3.0     let yourHeight = yourWidth      return CGSize(width: yourWidth, height: yourHeight) } 

You can also add these functions to get your spacing of the collectionViewCells correct:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {     return UIEdgeInsets.zero }  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 } 
like image 127
Kingalione Avatar answered Oct 03 '22 22:10

Kingalione