ios開發中,UICollectionView是一個極其重要的組件,我們通過自定義UICollectionViewFlowLayout可以實現一些極其復雜的布局。
項目demo地址為:
demo地址
這次主要實現的布局主要有以下三種:
-不規則高度瀑布流兩列排序
-瀑布流不規則高度多列排列
-橫向滑動第一個cell放大
主要介紹這三種布局通過自定義UICollectionViewFlowLayout如何實現,demo的GitHub鏈接放在文末
瀑布流不規則高度兩列布局
在demo中的實現的文件名為firstViewController.m和waterFlowLayout.m,定義一個array數組,用于保存不規則的高度
@property (nonatomic, strong) NSMutableArray *array;//用于存儲高度數據
- (NSMutableArray *)array {
if (_array) {
return _array;
}
_array = [NSMutableArray arrayWithObjects:@(100),@(150),@(150),@(50),@(130),@(180),@(200),@(100),@(110),@(200), nil];
return _array;
}
總共10個高度數據,這個可以自己定義,寬度通過計算得到,使其剛好可以放下兩列數據
代碼如下
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
float width = self.view.bounds.size.width - 10 - 10 - 10;//10分別為左邊劇、右邊距以及minimumInteritemSpacing
float height = [[self.array objectAtIndex:indexPath.row] floatValue];
return CGSizeMake(width / 2, height);
}
我們先使用UICollectionViewFlowLayout看一下實現的效果圖
這種布局里面有很多空白,看上去很不舒服,我們想的是將其填滿,所以需要自定義UICollectionViewflowlayout實現,在其中我們需要使用到的自定義的方法的作用
//初始化自定義的flowLayout
- (void)prepareLayout {
//必須調用super
[super prepareLayout];
}
//滑動時會時時調用此方法 改變布局
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
}
//替換最終滑動的contentOffset, proposedContentOffset是預期滑動停止的位置
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
}
// 當collectionView bounds改變時,是否重新布局
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
//返回collectionView的最終大小
- (CGSize)collectionViewContentSize {
}
自定義flowLayout參考鏈接
為了實現瀑布流排列,我們需要知道每一行排列后第一列和第二列的最大的y值,因為只有兩列,所以我們可以通過奇偶判斷來進行實現(下面多列時會使用其他的思路,也適合于兩列的情況)
新建一個文件繼承自UICollectionViewFlowLayout,命名為waterFlowLayout
在.h文件中定義一個繼承自UICollectionViewDelegateFlowLayout的協議WaterFlowLayoutDelegate
并且
@property (nonatomic, weak) id<WaterFlowLayoutDelegate> delegate;
.h文件中定義一些屬性
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *itemAttributes;//存儲各個cell的屬性
@property (nonatomic) CGFloat xOffset;
@property (nonatomic) CGFloat yOffset;
@property (nonatomic) CGFloat maxOddY;//奇數時最大的y
@property (nonatomic) CGFloat maxEvenY;//偶數時最大的y
在.m文件中
- (void)prepareLayout {
[super prepareLayout];
//初始化定義的屬性
self.scrollDirection = UICollectionViewScrollDirectionVertical;//豎直方向滑動
self.itemAttributes = [NSMutableArray array];
self.xOffset = 0;
self.yOffset = 0;
self.maxOddY = 0;
self.maxEvenY = 0;
//獲取UICollectionView的一些基本屬性
//獲取元素個數
NSInteger count = [self.collectionView numberOfItemsInSection:0];
//獲取collectionView的組邊距
UIEdgeInsets sectionEdgeInsets = [self.delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:0];
//自定義屬性賦初值
self.xOffset = sectionEdgeInsets.left;
self.yOffset = sectionEdgeInsets.top;
self.maxOddY = self.yOffset;
self.maxEvenY = self.yOffset;
//對于每個cell
for (int i = 0; i < count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
//獲取對應的cell的大小
CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
if (i % 2 == 0) {
//如果是偶數列,即左邊這列,因為i從0開始的,初始的xoffset設置為左邊距,初始的yOffset設置為距離頂部的邊距
self.xOffset = sectionEdgeInsets.left;
self.yOffset = self.maxEvenY;
} else {
//如果為奇數列,即右邊這列,xOffset為左邊距+cell的寬度+cell之間的間距
self.xOffset = sectionEdgeInsets.left + itemSize.width + self.minimumInteritemSpacing;
self.yOffset = self.maxOddY;
}
//獲取對應的indexPath的cell的屬性
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
//給cell賦值新的frame
attributes.frame = CGRectMake(self.xOffset, self.yOffset, itemSize.width, itemSize.height);
[self.itemAttributes addObject:attributes];
if (i % 2 == 0) {
//偶數列即左邊這列,maxEvenY最大的y偏移為初始的偏移maxEvenY + cell的高度 + cell豎向之間的距離
self.maxEvenY = self.maxEvenY + itemSize.height +
self.minimumLineSpacing;
} else {
//奇數列中,最大偏移同上
self.maxOddY = self.maxOddY + itemSize.height + self.minimumLineSpacing;
}
}
}
在上面中,兩列分別使用maxEvenY 和maxOddY來記錄兩邊的最大y偏移,并且對每個cell重新計算frame,存儲到itemAttributes中,接下來只要返回這個itemAttributes即可。
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.itemAttributes;
}
這樣之后,我們運行之后的效果圖為
我們可以看到,在滑到底部時,collectionView會有很大的剩余,為了解決這個問題,我們需要重新限制collectionView的大小,在自定義flowLayout中
- (CGSize)collectionViewContentSize {
//maxOddY和maxEvenY正好是我們計算y方向的偏移量,我們取其最大值
float height = MAX(self.maxOddY, self.maxEvenY);
return CGSizeMake(self.collectionView.bounds.size.width, height);
}
之后運行,得到的就是我們下面的效果圖
不規則的寬度和高度的排列
上面講了兩列的排列,通過奇偶來實現的,有很大的局限性,下面講的是:寬度固定,但是不是兩列,是多列的情況下,高度不固定的實現,文末會付上相應的github地址,其中的實現文件為secondViewController.m和waterFlowLayoutNew.m
我們首先在secondViewController中定義數組,分別存放自定義高度
@property (nonatomic, strong) NSMutableArray *heightArray;//用于存儲高度數據
- (NSMutableArray *)heightArray {
if (_heightArray) {
return _heightArray;
}
_heightArray = [NSMutableArray arrayWithObjects:@(100),@(150),@(150),@(50),@(130),@(180),@(200),@(100),@(110),@(200), nil];
return _heightArray;
}
對于每個collectionViewCell的大小設置為:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSInteger count = 3;//每行排列的cell的個數
float width = self.view.bounds.size.width - 10 * 2 - 10 * (count - 1);
float height = [[self.heightArray objectAtIndex:indexPath.row] floatValue];
return CGSizeMake(width / count, height);
}
通過count設置自定義的列數(這里以3列為例子,后面只需修改該數值即可)
初始時,使用UICollectionViewFlowLayout,此時的布局效果如下:
這個布局很顯然不滿足我們的要求,通過自定義flowLayout實現相應的效果
新建一個繼承自UICollectionViewLayout的類,命名為waterFlowLayoutNew,在該類中,定義一個協議繼承自UICollectionViewDelegateFlowLayout,代碼如下:
@protocol WaterFlowLayoutNewDelegate <UICollectionViewDelegateFlowLayout>
@end
@property (nonatomic, weak) id<WaterFlowLayoutNewDelegate> delegate;
然后定義相應的屬性
//每個cell的屬性數組
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *itemAttributes;
@property (nonatomic) CGFloat xOffset;
@property (nonatomic) CGFloat yOffset;
//每一行的個cell的個數
@property (nonatomic) NSInteger perLineCount;
在.m文件中,
- (void)prepareLayout {
[super prepareLayout];
//初始化定義的屬性
self.scrollDirection = UICollectionViewScrollDirectionVertical;
self.itemAttributes = [NSMutableArray array];
self.xOffset = 0;
self.yOffset = 0;
//獲取相應的collectionView的屬性
NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];
UIEdgeInsets sectionInsets = [self.delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:0];
self.xOffset = sectionInsets.left;
self.yOffset = sectionInsets.top;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
CGSize size = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
//因為cell的寬度是固定的(我們自定義的寬度都是一樣的,現在就是處理的是寬度固定、高度不固定的多列排列),所以我們可以求出每行的cell個數
NSInteger count = floor (self.collectionView.bounds.size.width - sectionInsets.left - sectionInsets.right + self.minimumInteritemSpacing) / (size.width + self.minimumInteritemSpacing);
self.perLineCount = count;
//定義一個數組,用于存儲每行每一個cell的yOffset,因為每個cell的高度不同,所以下一行的cell布局需要用到它
NSMutableArray *yOffsetArray = [NSMutableArray arrayWithCapacity:self.perLineCount];
for (int i = 0; i < itemCount;i++) {
//獲取每一個cell的大小
CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//當這一行還可以放下cell時
if (self.xOffset + sectionInsets.right + itemSize.width <= self.collectionView.bounds.size.width) {
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
//當布局的不是第一行的時候
if (yOffsetArray.count == self.perLineCount) {
//yOffset為同一列上一行的yOffset偏移量,存儲在數組中 + 行與行之間的間距
self.yOffset = [[yOffsetArray objectAtIndex:(i % self.perLineCount)] floatValue] + self.minimumLineSpacing;
}
attributes.frame = CGRectMake(self.xOffset, self.yOffset, itemSize.width, itemSize.height);
//存儲cell的屬性
[self.itemAttributes addObject:attributes];
//下一個cell的xOffset
self.xOffset = self.xOffset + itemSize.width + self.minimumInteritemSpacing;
if (yOffsetArray.count < self.perLineCount) {
//布局第一行時yOffset為空,沒法使用replace,所以使用addObject
[yOffsetArray addObject:@(self.yOffset + itemSize.height)];
} else {
//布局第二行及往后,數組不為空,直接替換相應的數組對象
[yOffsetArray replaceObjectAtIndex:(i % self.perLineCount) withObject:@(self.yOffset + itemSize.height)];
}
} else {
//當這一行放不下時,需要換行放置
self.xOffset = sectionInsets.left;
//從數組中獲取上一行同一列的yoffset + 行與行之間的間距
self.yOffset = [[yOffsetArray objectAtIndex:(i % self.perLineCount)] floatValue] + self.minimumLineSpacing;
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
attributes.frame = CGRectMake(self.xOffset, self.yOffset, itemSize.width, itemSize.height);
//存儲cell的屬性
[self.itemAttributes addObject:attributes];
//下一個cell的xOffset
self.xOffset = self.xOffset + itemSize.width + self.minimumInteritemSpacing;
self.yOffset = self.yOffset + itemSize.height;
//更新yOffsetArray數組
[yOffsetArray replaceObjectAtIndex:(i % self.perLineCount) withObject:@(self.yOffset)];
}
}
}
上面先算出每一行的cell的個數,然后創建一個同樣大小的數組,每放置一個cell,就將cell的最大偏移量yOffset存儲或者更新到yOffsetArray數組中,然后將得到的每個cell的attributes存儲到數組中itemAttributes中
//返回每個cell的屬性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.itemAttributes;
}
//更新collectionView的大小
- (CGSize)collectionViewContentSize {
return CGSizeMake(self.collectionView.bounds.size.width, self.yOffset);
}
最終得到的效果圖為(3列的情況下)
修改count為4,即是4列等寬度的情況
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSInteger count = 4;//每行排列的cell的個數
float width = self.view.bounds.size.width - 10 * 2 - 10 * (count - 1);
float height = [[self.heightArray objectAtIndex:indexPath.row] floatValue];
return CGSizeMake(width / count, height);
}
相應的效果圖為:
這種方法的適用性更廣,比2列情況下的奇偶解決思路要好一些。
橫向滑動時第一個cell放大的實現
要實現的最終效果如下:
先使用UICollectionViewFlowLayout來實現一個簡單的滑動,滑動方向設置為水平滑動。
設置cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(100, 100);
}
最終得到的效果圖為:
滑動過程中cell大小不會變化,下面開始使用自定義的flowLayout
新建一個文件繼承自UICollectionViewFlowLayout,命名為FirstCellZoomInLayoutTwo
在.h文件中,定義相應的協議,協議中定義一個協議方法,用于實現對第一個cell的frame放大
@protocol FirstCellZoomInLayoutTwoDelegate <UICollectionViewDelegateFlowLayout>
- (CGSize)sizeForFirstCell;
@end
.h文件中定義相應的協議
@property (nonatomic, weak) id<FirstCellZoomInLayoutTwoDelegate> delegate;
在.m文件中
- (void)prepareLayout {
[super prepareLayout];
//必須要設置,因為默認的滑動方向是豎直滑動
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;//設置滑動方向為水平滑動
}
在ThirdViewController.m中,遵守協議,實現相應的協議方法
- (CGSize)sizeForFirstCell {
return CGSizeMake(120, 150);
}
接著需要修改第一個cell的frame
在FirstCellZoomInLayoutTwo.m文件中
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
//獲取原有的所有cell的布局信息
NSArray *originalArr = [super layoutAttributesForElementsInRect:rect];
//獲取collectionView的相關屬性
UIEdgeInsets sectionInsets = [self.delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:0];
CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//因為加上了self.collectionView.contentoffset.x,所以first代表的是顯示在界面上的最左邊的cell
CGRect first = CGRectMake(sectionInsets.left + self.collectionView.contentOffset.x, sectionInsets.top + self.collectionView.contentOffset.y, itemSize.width, itemSize.height);
//需要放大的cell的大小
CGSize firstCellSize = [self.delegate sizeForFirstCell];
CGFloat totalOffset = 0;
for (UICollectionViewLayoutAttributes *attributes in originalArr) {
CGRect originFrame = attributes.frame;
//判斷兩個矩形是否相交,判斷cell與需要放大的cell的frame是否有相交,如果相交,需要修改cell的frame
if (CGRectIntersectsRect(first, originFrame)) {
//如果相交,獲取兩個矩形相交的區域
CGRect insertRect = CGRectIntersection(first, originFrame);
attributes.size = CGSizeMake(itemSize.width + (insertRect.size.width / itemSize.width) * (firstCellSize.width - itemSize.width), itemSize.height + (insertRect.size.width) / (itemSize.width) * (firstCellSize.height - itemSize.height));
//計算因為放大第一個導致的cell的中心點的偏移量
CGFloat currentOffsetX = attributes.size.width - itemSize.width;
attributes.center = CGPointMake(attributes.center.x + totalOffset + currentOffsetX / 2, attributes.center.y);
totalOffset = totalOffset + currentOffsetX;
} else {
//當cell的最小x值大于第一個cell的最大x值時,cell的偏移量需要加上totolOffset
if (CGRectGetMinX(originFrame) >= CGRectGetMaxX(first)) {
attributes.center = CGPointMake(attributes.center.x + totalOffset, attributes.center.y);
}
}
}
return originalArr;
}
上面處理的思路是:
判斷各個cell與第一個cell是否相交(只有第一個cell才能與其相交),相交的話將該cell的寬高設為放大后的寬高,中心點的偏移量為currentOffsetX的一半,如果不相交的話,中心點的偏移量為currentOffset,不用除以二
這樣之后的運行效果為:
可以看到此時的frame大小滑動的過程中會出現各種異常,這是因為collectionView的bounds發生變化,我們沒有及時更新導致的,需要加上以下方法
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
這是運行的效果圖為:
從上面的圖上可以看出,已經基本滿足要求,但是滑動后停留的位置不準,接下來需要對這個進行處理
在- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity方法中進行處理
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
//獲取collectionView的相關屬性
UIEdgeInsets sectionInsets = [self.delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:0];
CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
CGFloat finalPointX = 0;
//根據最終的偏移量計算出最終停留的cell的index值,向上取整
NSInteger index = ceil(proposedContentOffset.x / (itemSize.width + self.minimumInteritemSpacing));
//根據index值計算出相應的偏移量
finalPointX = (itemSize.width + self.minimumInteritemSpacing) * index;
//得到最終停留點
CGPoint finalPoint = CGPointMake(finalPointX, proposedContentOffset.y);
return finalPoint;
}
最終的效果圖為:
總結
通過自定義UICollectionViewFlowLayout可以實現一些復雜的布局效果,
demo地址