Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display 3 cells per row in UICollectionView?

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: Result What did I miss? I've come across some other SO posts but no luck so far.

like image 397
FlySoFast Avatar asked Oct 15 '15 04:10

FlySoFast


People also ask

What is UICollectionView flow layout?

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

What is the difference between UITableView and UICollectionView?

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.

Do Collectionview use cells?

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.


1 Answers

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)
}
like image 83
Jože Ws Avatar answered Sep 18 '22 02:09

Jože Ws