自定義UICollectionViewFlowLayout

在學(xué)習(xí)collectionView的時候最重要的是每一個cell位置布局.每一個cell的布局完全有一個類來控制UICollectionViewLayout 就是這個類.然而我們用的做多是他的子類UICollectionViewFlowLayout.流氏布局.
下面這個demo是在流氏布局的基礎(chǔ)上重寫得到的

下面是控制器.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是不變的,就在這里面布局 找到規(guī)律改變每一個 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{
//獲得當(dāng)前屏幕上所有的Attrs
NSArray <UICollectionViewLayoutAttributes*> *arrayAttrs = [super layoutAttributesForElementsInRect:rect];
  //計算可見范圍內(nèi) 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);
    //根據(jù)cell 距離中心點的這個動態(tài) 變化的距離制造一個縮放比例.

    CGFloat scale = 1 - distance / (self.collectionView.frame.size.width /2.0);
    
    //當(dāng)?shù)竭_邊界的時候 scale = 0 當(dāng)時到達中心的時候 scale = 1;
    attr.transform = CGAffineTransformMakeScale(scale, scale);
}

return arrayAttrs;
}

/**
* 這個方法的返回值,就決定了collectionView停止?jié)L動時的偏移量
*/

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

// 得到顯示在屏幕上的 那塊區(qū)域的坐標(biāo)和大小
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的坐標(biāo)
CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;

//這只是一個 很大的數(shù)字
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的內(nèi)容視圖.

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

效果圖

2016-07-16 22_04_27.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容