自定义UICollectionViewFlowLayout

作者: 大墙66370 | 来源:发表于2016-07-16 22:06 被阅读964次

在学习collectionView的时候最重要的是每一个cell位置布局.每一个cell的布局完全有一个类来控制UICollectionViewLayout 就是这个类.然而我们用的做多是他的子类UICollectionViewFlowLayout.流氏布局.
下面这个demo是在流氏布局的基础上重写得到的

下面是控制器.h

//
//  ViewController.h
//  照片流水CollectionView
//
//   Created by 3D on 16/7/15.
//  Copyright © 2016年 3D. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController :  UIViewController
@end

下面是控制器.m

 //
 //  ViewController.m
 //  照片流水CollectionView
 //
 //  Created by 3D on 16/7/15.
 //  Copyright © 2016年 3D. All rights reserved.
 //

 #import "ViewController.h"
 #import "liushuiLayout.h"
 #import "testCollectionViewCell.h"
 @interface ViewController ()    <UICollectionViewDataSource,UICollectionViewDelegate>
 @property(nonatomic,strong)UICollectionView *collectionView;
 @end

@implementation ViewController

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 20;
}

  // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
testCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

cell.imageName = @"2";
cell.lableName = [NSString stringWithFormat:@"%ld",indexPath.item];
return cell;
}

-(UICollectionView *)collectionView{
if (!_collectionView) {
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:[[liushuiLayout alloc]init]];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[testCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
}
return _collectionView;
}

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addSubview:self.collectionView];
 }

 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be  recreated.
}

@end

下面是重写的cell.h

#import <UIKit/UIKit.h>

@interface testCollectionViewCell :     UICollectionViewCell

@property(nonatomic,strong)NSString *lableName;
@property(nonatomic,strong)NSString *imageName;
@end

下面是重写cell.m

#import "testCollectionViewCell.h"

@interface testCollectionViewCell ()
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UILabel *lable;
@end

@implementation testCollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
    UIImageView *imageView = [[UIImageView alloc]init];
    self.backgroundView = imageView;
    self.imageView = imageView;
    
    UILabel *lable = [[UILabel alloc]init];
    self.lable = lable;
    self.lable.textAlignment = NSTextAlignmentCenter;
    self.lable.backgroundColor = [UIColor grayColor];
    self.lable.textColor = [UIColor greenColor];
    self.lable.frame = CGRectMake(0, 0, 50, 50);
    [self.imageView addSubview:self.lable];
    
}
return self;
}

-(void)setImageName:(NSString *)imageName{
_imageName = imageName;
self.imageView.image = [UIImage imageNamed:_imageName];
}

-(void)setLableName:(NSString *)lableName{
_lableName = lableName;
self.lable.text = _lableName;
}
@end

灵魂布局.h

#import <UIKit/UIKit.h>

@interface liushuiLayout : UICollectionViewFlowLayout
@end

灵魂布局.m

#import "liushuiLayout.h"

@interface liushuiLayout ()
@property(nonatomic,strong)NSMutableArray *arr;
@end


@implementation liushuiLayout

//保存所有的布局项
- (NSMutableArray *)arr {
if(_arr == nil) {
    _arr = [[NSMutableArray alloc] init];
}
return _arr;
}

-(instancetype)init{
if (self = [super init]) {
    NSLog(@"000000");
    self.itemSize = CGSizeMake(120, 120);
    self.minimumInteritemSpacing = 500;
    self.minimumLineSpacing = 2;
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}
return self;
}

-(void)prepareLayout{
[super prepareLayout];
//如果布局是死的 就是每个cell的frem是不变的,就在这里面布局 找到规律改变每一个 attrs的fream就好了
//    NSInteger count =   [self.collectionView numberOfItemsInSection:0];
//    for (int i = 0; i < count; i++) {
 //        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
//        UICollectionViewLayoutAttributes *attrs = [self  layoutAttributesForItemAtIndexPath:indexPath];
//        
//        [self.arr addObject:attrs];
//    }

//   self.itemSize = CGSizeMake(120, 120);
 //  self.minimumInteritemSpacing = 500;
//   self.minimumLineSpacing = 2;
  // self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}

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


-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
//获得当前屏幕上所有的Attrs
NSArray <UICollectionViewLayoutAttributes*> *arrayAttrs = [super layoutAttributesForElementsInRect:rect];
  //计算可见范围内 collectionView 在屏幕中的 中心点位置.
CGFloat centerX = self.collectionView.frame.size.width/2.0 + self.collectionView.contentOffset.x;
//
for (UICollectionViewLayoutAttributes *attr in arrayAttrs) {
   //屏幕中 cell的中心点距离屏幕的中心点的距离 (可知道这个距离最小是0 最大是self.collectionView.frame.size.width/2)
    CGFloat distance = ABS(attr.center.x - centerX);
    //根据cell 距离中心点的这个动态 变化的距离制造一个缩放比例.

    CGFloat scale = 1 - distance / (self.collectionView.frame.size.width /2.0);
    
    //当到达边界的时候 scale = 0 当时到达中心的时候 scale = 1;
    attr.transform = CGAffineTransformMakeScale(scale, scale);
}

return arrayAttrs;
}

/**
* 这个方法的返回值,就决定了collectionView停止滚动时的偏移量
*/

-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{

// 得到显示在屏幕上的 那块区域的坐标和大小
CGRect rect = CGRectZero;
rect.origin.y = 0;
rect.origin.x = proposedContentOffset.x;
rect.size = self.collectionView.frame.size;

// 得到还没有 缩放前的 attr
NSArray <UICollectionViewLayoutAttributes*> *arrayAttrs = [super layoutAttributesForElementsInRect:rect];
//计算可见范围[屏幕上 collectionView中心点的x的坐标
CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;

//这只是一个 很大的数字
CGFloat minDistance = MAXFLOAT;
for (UICollectionViewLayoutAttributes *attr in arrayAttrs) {
    //便利算出 每一个attr的中心点距离 centerX的距离并得到最小距离
    if (ABS(minDistance) > ABS(attr.center.x - centerX)) {
        
        minDistance  = attr.center.x - centerX; //
    }
}
//修改 原来的偏移量
proposedContentOffset.x += minDistance;
return proposedContentOffset;
}
@end

配合这一张图来理解 灵魂布局.m
黑色框框代表屏幕
红色框框代表collectionView的内容视图.

8B1CF3FE-6ED1-46E4-A94A-2A2F904B6BF5.png

效果图

2016-07-16 22_04_27.gif

相关文章

网友评论

  • 纳木错_grace:你好,请问如果实现分组效果的话,在自定义FlowLayout里怎么处理组头或组尾的布局。谢谢!

本文标题:自定义UICollectionViewFlowLayout

本文链接:https://www.haomeiwen.com/subject/wfyujttx.html