Reputation: 1932
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.
Upvotes: 6
Views: 25900
Reputation: 1510
itemSpacing = "Spacing size between cell."
itemsInOneLine = "Number of item which you want to display in single row."
collectionWidth = "Width of your collection view"
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = (collectionWidth) - itemSpacing * CGFloat(itemsInOneLine - 1)
layout.itemSize = CGSize(width:floor(width/CGFloat(itemsInOneLine)),height:width/CGFloat(itemsInOneLine))
Upvotes: 0
Reputation: 1814
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)
}
Upvotes: 11
Reputation: 20786
//Make use of UICollectionViewDelegateFlowLayout Protocol
class RVC: UICollectionViewController {
//some code
}
extension RVC: UICollectionViewDelegateFlowLayout{
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
var collectionViewSize = collectionView.frame.size
collectionViewSize.width = collectionViewSize.width/3.0 //Display Three elements in a row.
collectionViewSize.height = collectionViewSize.height/4.0
return collectionViewSize
}
For more information go through below link.
UICollectionView Set number of columns
Upvotes: 8
Reputation: 47
You don't have to do it by coding. You just have to do in xib.as per iPhone 5 or 5s width become 320. and you want to show 3 cells per row so u have to do 320/3 and as per you get whatever answer your cell size is as per result.If any doubt of my answer ask me.
Upvotes: -6