UICollectionView的基本应用和自定义布局

UICollectionView的自定义布局,在写篇文章之前,自己在方面遇到不少问题,首先感谢帮助过我的人,自己也在网上找了不少资料,如有不足之处,请多多指教。

UICollectionView 基本使用
  • UICollectionView使用注意点
    • 1.创建UICollectionView必须要有布局参数(UICollectionViewFlowLayout比如流水性布局,UICollectionViewLayout空白布局,需要自己写cell样式)
    • 2.cell必须通过注册
    • 3.cell必须自定义,系统cell没有任何子控件
//注册cell的ID
 static NSString * const ID = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];
     // 创建布局参数
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置 item的大小
    layout.itemSize = CGSizeMake(60, 60);
    //设置最小item的间距
    layout.minimumInteritemSpacing = 5;
    //设置最小行间距
    layout.minimumLineSpacing = 5;
    
    // 创建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];
    
    // 设置数据源
    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创建cell


#import 

@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的基本应用和自定义布局_第1张图片
UICollectionView基本使用.png
自定义布局
//自定义布局需要知道的几个方法

//作用:计算cell的布局
//调用:第一次布局collectionView或者collectionView刷新的时候调用
//初始化布局
- (void)prepareLayout;
 

/*
 UICollectionViewLayoutAttributes:确定cell的尺寸
 一个UICollectionViewLayoutAttributes对象就对应一个cell
 拿到UICollectionViewLayoutAttributes相当于拿到cell
 */
// 返回数组中的 UICollectionViewLayoutAttributes 布局属性
/// 这个方法返回一个数组, 数组存放rect的范围内所有元素的布局属性,返回的数组决定了rect范围内所有的元素排布(frame)
 - (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
 
/**
 * 当 collectionView的显示范围繁盛改变的时候,是否需要重新刷新布局
 */
 - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;
 
/**
 *  这个方法的返回值,就决定了collectionView停止滚动时的偏移量
 *  proposedContentOffset  最终的偏移量
 *  velocity 滚动速率  这个参数可以了解到滚动的方向
 */
 - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity; 

/// 每一个item对应cell的UICollectionViewLayoutAttributes属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;

//collectionView内容大小
 - (CGSize)collectionViewContentSize;

UICollectionView的基本应用和自定义布局_第2张图片
效果图.gif

自定义布局的例子-(效果如上图)

*****************控制器****************

#import "ViewController.h"

#import "CCLineLayout.h"

#import "CCCell.h"

#import "CCCircleLayout.h"

@interface ViewController ()

@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 *)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的第一个布局样式******************

计算图:

UICollectionView的基本应用和自定义布局_第3张图片
距离中心线的计算图.png
#import 

@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;
    // 内边距
    self.sectionInset = UIEdgeInsetsMake(0, det, 0, det);
}


/**
 * 当 collectionView的显示范围发生改变的时候,是否需要重新刷新布局
 */

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    
    
    return YES;
}



/**
 *   UICollectionViewLayoutAttributes
 *  1.一个cell对应一个UICollectionViewLayoutAttributes对象
 *  2.UICollectionViewLayoutAttributes对象决定了cell的frame
 */

/// 这个方法返回一个数组, 数组存放rect的范围内所有元素的布局属性,返回的数组决定了rect范围内所有的元素排布(frame)

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
  //获取布局属性数组
    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);
        //根据间距 算出比例值
        CGFloat scale = 1- del/(self.collectionView.bounds.size.width *0.5) *0.25;
        //缩放
        attr.transform = CGAffineTransformMakeScale(scale, scale);

    }
    
    return array;
    
   
}

/**
 *  这个方法的返回值,就决定了collectionView停止滚动时的偏移量
 *  proposedContentOffset  最终的偏移量
 *  velocity 滚动速率  这个参数可以了解到滚动的方向
 */
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
    
    CGFloat collectionViewW = self.collectionView.bounds.size.width;
    //最终偏移量
    CGPoint targetP = [super targetContentOffsetForProposedContentOffset:proposedContentOffset withScrollingVelocity:velocity];
    //获取最终显示的区域
    CGRect targetRect = CGRectMake(targetP.x, 0, collectionViewW, MAXFLOAT);

    //获取布局属性数组
    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 

@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];
    }
    
}


/// 返回数组中的 UICollectionViewLayoutAttributes 布局属性
- (NSArray *)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;
    
    //创建 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





你可能感兴趣的:(UICollectionView的基本应用和自定义布局)