Iglistkit: how to have an grid layout with dynamic items per row

Created on 22 Dec 2016  路  6Comments  路  Source: Instagram/IGListKit

I'd like to have a layout where the number of items per row varies depending on the width of the device (e.g. iPhone vs iPad or during an orientation change) and the items are equally spaced in the view i.e. margins around as well as between them are equal

at the moment the way I am doing this is

  • in my UIViewController I define an IGListAdapter and assign to it a IGListCollectionView and an IGListAdapterDataSource

  • in my IGListAdapterDataSource in the listAdapter I return a custom IGListSectionController which I use to set the data to be displayed in each item

  • in my IGListCollectionView I use a IGListGridCollectionViewLayout where I calculate the width (a fixed width) and height of each item (all items have the same dimensions) and set the itemSize, minimumInteritemSpacing and minimumLineSpacing attributes of the layout

At first this seemed to have worked: I got 1 item on the iPhone 5s simulator and 2 on portrait orientation of the iPad Air simulator which when I rotate to landscape became 3. However the items were not centered on the display, though the spacing between the items seems equal.

Is this the correct approach ?

(I am very new to Swift and iOS so I greatly appreciate your help)

question

Most helpful comment

@rnystrom I think we can add an alignment style enum to the grid layout.

All 6 comments

@gvlachos are you trying to space the items across the width of the collection view? Sometimes called justified (see the "space between"). Or are you trying to get them centered?

That might require updating the IGListGridCollectionViewLayout to be more flexible in its layout. Atm its pretty locked down.

Your setup looks right though!

@rnystrom oh ok, my description was a bit off. I am trying to have them justified with space-around, so all white space (around the items) in a row is equal.

Ahh, so centered w/ the same interitem spacing between them. Have you tried setting minimumInteritemSpacing on the layout itself and not using the API on the section controller?

yes I set layout.minimumInteritemSpacing to a fixed value (CGFloat(10.0)) and I do get equal spacing between the items, so that works. Thinking about it I would like to be able to calculate it dynamically so the left most and right most item are at the edge of the view. Will try that next. Thanx for your help!

@rnystrom I think we can add an alignment style enum to the grid layout.

I think we can add an alignment style enum to the grid l

did add an alignment style ?

Was this page helpful?
0 / 5 - 0 ratings