I am using a UICollectionView in my project, where there are multiple cells of differing widths on a line. According to: https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html
it spreads the cells out across the line with equal padding. This happens as expected, except I want to left justify them, and hard code a padding width.
I figure I need to subclass UICollectionViewFlowLayout, however after reading some of the tutorials etc online I just don't seem to get how this works.
Based on all answers, I change a bit and it works good for me
The question has been up a while but there's no answer and it's a good question. The answer is to override one method in the UICollectionViewFlowLayout subclass:
As recommended by Apple, you get the layout attributes from super and iterate over them. If it's the first in the row (defined by its origin.x being on the left margin), you leave it alone and reset the x to zero. Then for the first cell and every cell, you add the width of that cell plus some margin. This gets passed to the next item in the loop. If it's not the first item, you set it's origin.x to the running calculated margin, and add new elements to the array.
The problem with UICollectionView is that it tries to automatically fit the cells in the available area. I have done this by first defining number of rows and columns and then defining the cell size for that row and column
1) To define Sections (Rows) of my UICollectionView:
2) To define number of items in a section. You can define different number of items for every section. you can get section number using 'section' parameter.
3) To define Cell size for each section and row separately. You can get section number and row number using the 'indexPath' parameter i.e.
[indexPath section]
for section number and[indexPath row]
for row number.4) Then you can display your cells in rows and sections using:
NOTE: In UICollectionView
Mike Sand's answer is good but i had experienced some issues with this code (Like lengthy cell clipped out). And new code:
The other solutions in here not work properly when the line is composed by only 1 item or are over complicated.
Based on the example given by Ryan, I changed the code to detect a new line by inspecting the Y position of the new element. Very simple and quick in performance.
Swift:
If you want to have supplementary views keep their size, add the following at the top of the closure in the
forEach
call:Objective-C: