引言
collcetionView 橫向分頁排版現(xiàn)在在App首頁頭部視圖菜單里面用的比較多。今天分享一哈實(shí)現(xiàn)方法。

true.png
這種界面分分鐘肯定會(huì)想到用collectionview來做,實(shí)現(xiàn)也很簡(jiǎn)單,但是結(jié)果你得到的會(huì)是下面這種界面(順序完全不是你想要的)

false.png
這是collectionview橫向滑動(dòng)默認(rèn)的布局方式,想要實(shí)現(xiàn)按照你想要的順序的布局方式的話必須自定義collectionviewflowlayout子類來實(shí)現(xiàn)了,廢話不多說直接上代碼。
- (void)prepareLayout {
[super prepareLayout];
[self.attArray removeAllObjects];
//定義當(dāng)前行數(shù)、頁數(shù)變量
NSInteger lineNum = 1;
NSInteger page = 0;
//定義itemsize
NSInteger originX = self.collectionView.bounds.size.width;
CGFloat attWidth = (SCREEN_WIDTH - 22) / 5;
CGFloat attHeight = (SCREEN_WIDTH - 22) / 5.5;
NSInteger items = [self.collectionView numberOfItemsInSection:0];
for (NSInteger i = 0; i < items; i ++) {
NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
//因?yàn)槲沂且恍酗@示5個(gè),所以取計(jì)算5的余數(shù),如果==0就換行,一來i = 0,所以lineNum初始值為0,從第一行開始添加
if (i % 5 == 0) {
lineNum = lineNum == 0 ? 1 : 0;
}
//超過10個(gè)就加一頁,讓x坐標(biāo)加上頁數(shù) * collectionview寬度
if ((NSInteger)(i / 10) >= 0) {
page = i / 10;
}
//計(jì)算frame
att.frame = CGRectMake((i % 5) * attWidth + (originX * page), lineNum * (attHeight + self.minimumInteritemSpacing) + self.sectionInset.top, attWidth, attHeight);
[self.attArray addObject:att];
}
}
- (CGSize)collectionViewContentSize {
NSInteger items = [self.collectionView numberOfItemsInSection:0];
NSInteger pages = 0;
if (items % 10 == 0) {
pages = items / 10;
} else {
pages = items / 10 + 1;
}
return CGSizeMake(CGRectGetWidth(self.collectionView.frame) * pages, 0);
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray *array = [NSMutableArray array];
for (UICollectionViewLayoutAttributes *att in self.attArray) {
if (CGRectIntersectsRect(rect, att.frame)) {
[array addObject:att];
}
}
return array;
}