如何在UICollectionView中每行显示3个单元格? [英] How to display 3 cells per row in UICollectionView?
本文介绍了如何在UICollectionView中每行显示3个单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我根据这篇文章使用了自定义流程布局. 这是我的实现:
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
这就是我得到的: 我错过了什么?我遇到过其他一些SO帖子,但到目前为止还没有运气.
This is what I've got: What did I miss? I've come across some other SO posts but no luck so far.
推荐答案
Swift 3.0.适用于水平和垂直滚动方向以及可变间距
声明每行所需的单元格数量
Declare number of cells you want per row
let numberOfCellsPerRow: CGFloat = 3
配置flowLayout
以呈现指定的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)
}
这篇关于如何在UICollectionView中每行显示3个单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文