I used a custom flow layout according to this post. Here is my implementation:
@implementation CustomLayout
-(void)prepareLayout{
[super prepareLayout];
// [self invalidateLayout];
if(self.collectionView){
CGSize newItemSize=self.itemSize;
// Number of items per row
int itemsPerRow=3;
float totalSpacing=self.minimumLineSpacing*(itemsPerRow-1);
newItemSize.width=(self.collectionView.bounds.size.width -totalSpacing)/itemsPerRow;
if(self.itemSize.height>0){
float itemAspectRatio=self.itemSize.width/self.itemSize.height;
newItemSize.height=newItemSize.width/itemAspectRatio;
}
[self setItemSize:newItemSize];
}
}
@end
This is what I've got:
What did I miss? I've come across some other SO posts but no luck so far.
A layout object that organizes items into a grid with optional header and footer views for each section.
For the listing details of each item, people use UITableView because it shows more info on each item. The UICollectionView class manages an ordered collection of data items and presents them using customizable layouts.
The collection view presents items onscreen using a cell, which is an instance of the UICollectionViewCell class that your data source configures and provides. In addition to its cells, a collection view can present data using other types of views.
Swift 3.0. Works for both horizontal and vertical scroll directions and variable spacing
Declare number of cells you want per row
let numberOfCellsPerRow: CGFloat = 3
Configure flowLayout
to render specified numberOfCellsPerRow
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1)*horizontalSpacing)/numberOfCellsPerRow
flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With