UICollectionView的自定義布局,在寫篇文章之前谭期,自己在方面遇到不少問題个盆,首先感謝幫助過我的人,自己也在網(wǎng)上找了不少資料舍沙,如有不足之處近上,請多多指教。
UICollectionView 基本使用
- UICollectionView使用注意點
- 1.創(chuàng)建UICollectionView必須要有布局參數(shù)(UICollectionViewFlowLayout比如流水性布局,UICollectionViewLayout空白布局拂铡,需要自己寫cell樣式)
- 2.cell必須通過注冊
- 3.cell必須自定義,系統(tǒng)cell沒有任何子控件
//注冊cell的ID
static NSString * const ID = @"cell";
- (void)viewDidLoad {
[super viewDidLoad];
// 創(chuàng)建布局參數(shù)
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//設置 item的大小
layout.itemSize = CGSizeMake(60, 60);
//設置最小item的間距
layout.minimumInteritemSpacing = 5;
//設置最小行間距
layout.minimumLineSpacing = 5;
// 創(chuàng)建UICollectionView:黑色
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
collectionView.backgroundColor = [UIColor brownColor];
collectionView.center = self.view.center;
collectionView.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 200);
[self.view addSubview:collectionView];
// 設置數(shù)據(jù)源
collectionView.dataSource = self;
// 注冊cell
[collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PhotoCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
NSString *imageName = [NSString stringWithFormat:@"%ld",indexPath.item + 1];
cell.image = [UIImage imageNamed:imageName];
return cell;
}
xib創(chuàng)建cell
#import <UIKit/UIKit.h>
@interface PhotoCell : UICollectionViewCell
@property (nonatomic, strong) UIImage *image;
@end
//.m文件
#import "PhotoCell.h"
@interface PhotoCell ()
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@end
@implementation PhotoCell
- (void)awakeFromNib {
[super awakeFromNib];
}
- (void)setImage:(UIImage *)image
{
_image = image;
_photoView.image = image;
}
@end
UICollectionView基本使用.png
自定義布局
//自定義布局需要知道的幾個方法
//作用:計算cell的布局
//調(diào)用:第一次布局collectionView或者collectionView刷新的時候調(diào)用
//初始化布局
- (void)prepareLayout;
/*
UICollectionViewLayoutAttributes:確定cell的尺寸
一個UICollectionViewLayoutAttributes對象就對應一個cell
拿到UICollectionViewLayoutAttributes相當于拿到cell
*/
// 返回數(shù)組中的 UICollectionViewLayoutAttributes 布局屬性
/// 這個方法返回一個數(shù)組壹无, 數(shù)組存放rect的范圍內(nèi)所有元素的布局屬性葱绒,返回的數(shù)組決定了rect范圍內(nèi)所有的元素排布(frame)
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
/**
* 當 collectionView的顯示范圍繁盛改變的時候,是否需要重新刷新布局
*/
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;
/**
* 這個方法的返回值斗锭,就決定了collectionView停止?jié)L動時的偏移量
* proposedContentOffset 最終的偏移量
* velocity 滾動速率 這個參數(shù)可以了解到滾動的方向
*/
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity;
/// 每一個item對應cell的UICollectionViewLayoutAttributes屬性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath地淀;
//collectionView內(nèi)容大小
- (CGSize)collectionViewContentSize;
效果圖.gif
自定義布局的例子-(效果如上圖)
*****************控制器****************
#import "ViewController.h"
#import "CCLineLayout.h"
#import "CCCell.h"
#import "CCCircleLayout.h"
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) NSMutableArray *imageArray;
/**<#class#>*/
@property (nonatomic, weak) UICollectionView *collerView;
@end
@implementation ViewController
static NSString *const ID = @"cell";
- (NSMutableArray *)imageArray {
if (!_imageArray) {
_imageArray = [NSMutableArray array];
for (int i = 0; i< 20 ;i ++) {
[_imageArray addObject:[NSString stringWithFormat:@"%zd",i + 1]];
}
}
return _imageArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
CCLineLayout *layout = [[CCLineLayout alloc] init];
layout.itemSize = CGSizeMake(100, 100);
CGFloat w = self.view.frame.size.width;
CGRect frame = CGRectMake(0, 150, w, 200);
UICollectionView *collerView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
collerView.delegate = self;
collerView.dataSource = self;
[self.view addSubview:collerView];
self.collerView = collerView;
//注冊cell
[collerView registerNib:[UINib nibWithNibName:NSStringFromClass([CCCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if ([self.collerView.collectionViewLayout isKindOfClass:[CCLineLayout class]]) {
[self.collerView setCollectionViewLayout:[[CCCircleLayout alloc] init] animated:YES];
} else {
CCLineLayout *layout = [[CCLineLayout alloc] init];
layout.itemSize = CGSizeMake(100, 100);
[self.collerView setCollectionViewLayout:layout animated:YES];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.imageArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.imageNmae = self.imageArray[indexPath.item];
return cell;
}
//MARK:UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
[self.imageArray removeObjectAtIndex:indexPath.item];
[self.collerView deleteItemsAtIndexPaths:@[indexPath]];
}
@end
********************cell的第一個布局樣式******************
計算圖:
距離中心線的計算圖.png
#import <UIKit/UIKit.h>
@interface CCLineLayout : UICollectionViewFlowLayout
@end
#import "CCLineLayout.h"
@implementation CCLineLayout
///布局的初始化操作
- (void)prepareLayout {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
CGFloat det = (self.collectionView.frame.size.width - self.itemSize.width)*0.5;
// 內(nèi)邊距
self.sectionInset = UIEdgeInsetsMake(0, det, 0, det);
}
/**
* 當 collectionView的顯示范圍發(fā)生改變的時候,是否需要重新刷新布局
*/
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
/**
* UICollectionViewLayoutAttributes
* 1.一個cell對應一個UICollectionViewLayoutAttributes對象
* 2.UICollectionViewLayoutAttributes對象決定了cell的frame
*/
/// 這個方法返回一個數(shù)組岖是, 數(shù)組存放rect的范圍內(nèi)所有元素的布局屬性帮毁,返回的數(shù)組決定了rect范圍內(nèi)所有的元素排布(frame)
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
//獲取布局屬性數(shù)組
NSArray *array = [super layoutAttributesForElementsInRect:self.collectionView.bounds];
//更改布局屬性
for (UICollectionViewLayoutAttributes *attr in array) {
//獲取到cell的中心點
CGFloat cellCenterX = attr.center.x;
// del是cell中心點 距離 collectionView中心點的距離
CGFloat del = fabs((cellCenterX - self.collectionView.contentOffset.x) - self.collectionView.bounds.size.width *0.5);
//根據(jù)間距 算出比例值
CGFloat scale = 1- del/(self.collectionView.bounds.size.width *0.5) *0.25;
//縮放
attr.transform = CGAffineTransformMakeScale(scale, scale);
}
return array;
}
/**
* 這個方法的返回值,就決定了collectionView停止?jié)L動時的偏移量
* proposedContentOffset 最終的偏移量
* velocity 滾動速率 這個參數(shù)可以了解到滾動的方向
*/
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
CGFloat collectionViewW = self.collectionView.bounds.size.width;
//最終偏移量
CGPoint targetP = [super targetContentOffsetForProposedContentOffset:proposedContentOffset withScrollingVelocity:velocity];
//獲取最終顯示的區(qū)域
CGRect targetRect = CGRectMake(targetP.x, 0, collectionViewW, MAXFLOAT);
//獲取布局屬性數(shù)組
NSArray *arry = [super layoutAttributesForElementsInRect:targetRect];
//最小的間距
CGFloat min = MAXFLOAT;
for (UICollectionViewLayoutAttributes *arrt in arry) {
//獲取距離中心點距離
CGFloat del = (arrt.center.x - targetP.x) - self.collectionView.bounds.size.width *0.5;
//找最小距離
if (fabs(min) > fabs(del)) {
min = del;
}
}
targetP.x += min;
if (targetP.x < 0) {
targetP.x = 0;
}
return targetP;
}
@end
*******************cell的第二個布局樣式***************
#import <UIKit/UIKit.h>
@interface CCCircleLayout : UICollectionViewLayout
@end
#import "CCCircleLayout.h"
@interface CCCircleLayout()
@property (nonatomic, strong) NSMutableArray *attArray;
@end
@implementation CCCircleLayout
- (NSMutableArray *)attArray {
if (!_attArray) {
_attArray = [NSMutableArray array];
}
return _attArray;
}
//初始化布局
- (void)prepareLayout {
[super prepareLayout];
[self.attArray removeAllObjects];
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (int i = 0; i < count; i ++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
UICollectionViewLayoutAttributes *atts = [self layoutAttributesForItemAtIndexPath:indexPath];
[self.attArray addObject:atts];
}
}
/// 返回數(shù)組中的 UICollectionViewLayoutAttributes 布局屬性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.attArray;
}
/// 每一個item對應cell的UICollectionViewLayoutAttributes屬性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
NSInteger count = [self.collectionView numberOfItemsInSection:0];
//設置圓心半徑
CGFloat radius = 70;
//圓心的位置
CGFloat oX = self.collectionView.frame.size.width *0.5;
CGFloat oY = self.collectionView.frame.size.height *0.5;
//創(chuàng)建 UICollectionViewLayoutAttributes屬性
UICollectionViewLayoutAttributes *attri = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
//設置寬高
attri.size = CGSizeMake(50, 50);
CGFloat angle = ( 2 * M_PI /count) *indexPath.item;
CGFloat centerX = oX + radius *sin(angle);
CGFloat centerY = oY + radius*cos(angle);
attri.center = CGPointMake(centerX, centerY);
return attri;
}
@end