iOS开发自定义流水布局

//集成UICollectionViewFlowLayout 自己写的布局

//  SJBFlowLayout.m

//  自定义流水布局

//

//  Created by zyyt on 16/7/20.

//  Copyright © 2016年 sjb. All rights reserved.

//

 

#import "SJBFlowLayout.h"

 

/*******分割线*******分割线********分割线*******分割线 *********分割线*********分割线***********/ 

@implementation SJBFlowLayout

 

/**

 //告诉布局对象去更像布局

 Tells the layout object to update the current layout.

 

 Layout updates occur the first time the collection view presents its content and whenever the layout is invalidated explicitly or implicitly because of a change to the view. 

 //在布局每一次更新的时候,collection都会唤醒这个方法

 During each layout update, the collection view calls this method first to give your layout object a chance to prepare for the upcoming layout operation.

 //这个方法默认什么也没实现    子类可以重写这个方法和用它去组建数据结构或实现任一个

 The default implementation of this method does nothing. Subclasses can override it and use it to set up data structures or perform any initial computations needed to perform the layout later.

 **/

 

- (void)prepareLayout

{

    [super prepareLayout];

    

    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;

    

    /*

     The distance that the content view is inset from the enclosing scroll view.

     Use this property to add to the scrolling area around the content. The unit of size is points. The default value is UIEdgeInsetsZero.

     

     */

    self.collectionView.contentInset  =  UIEdgeInsetsMake(0, inset, 0, inset);

    

}

 

/*Asks the layout object if the new bounds require a layout update.

The new bounds of the collection view.

Parameters

newBounds

The new bounds of the collection view.

Returns YES if the collection view requires a layout update or NO if the layout does not need to change.

*/

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

{

    return YES;

}

 

/*

 Returns the layout attributes for all of the cells and views in the specified rectangle.

 The rectangle (specified in the collection view’s coordinate system) containing the target views.

 Parameters

 rect

 The rectangle (specified in the collection view’s coordinate system) containing the target views.

 Returns An array of UICollectionViewLayoutAttributes objects representing the layout information for the cells and views.

 */

-  (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect

{

    

    NSArray * attArr = [super layoutAttributesForElementsInRect:rect];

    

    /*

     The collection view object currently using this layout object. (read-only)

     The collection view object sets the value of this property when a new layout object is assigned to it.

      */

    CGFloat  centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;

    

    for (int i=0; i<attArr.count; i++) {

        

        

        UICollectionViewLayoutAttributes * att = attArr[i];

        CGFloat delta = ABS(att.center.x - centerX);

        

        CGFloat scale = 1 - delta / self.collectionView.bounds.size.width;

        

        att.transform = CGAffineTransformMakeScale(scale, scale);

       

        }

    

    

    return attArr;

}

 

 

/*

 Returns the point at which to stop scrolling.

 The proposed point (in the collection view’s content view) at which to stop scrolling. This is the value at which scrolling would naturally stop if no adjustments were made. The point reflects the upper-left corner of the visible content.

 Parameters

 proposedContentOffset

 The proposed point (in the collection view’s content view) at which to stop scrolling. This is the value at which scrolling would naturally stop if no adjustments were made. The point reflects the upper-left corner of the visible content.

 velocity

 The current scrolling velocity along both the horizontal and vertical axes. This value is measured in points per second.

 Returns The content offset that you want to use instead.

 */

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

{

    CGRect rect;

    

    rect.origin.y = 0;

    rect.origin.x =  proposedContentOffset.x;

    rect.size.width = self.collectionView.bounds.size.width;

    rect.size.height = self.collectionView.bounds.size.height;

    

    NSArray * attArr = [super layoutAttributesForElementsInRect:rect];

    

    //The point at which the origin of the content view is offset from the origin of the scroll view.

    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;

    

    

    CGFloat mindel = MAXFLOAT;

    

    for (int i= 0; i<attArr.count; i++) {

        

        UICollectionViewLayoutAttributes * attributes = attArr[i];

        

        if ( ABS(mindel)  > ABS(attributes.center.x - centerX)) {

            mindel = attributes.center.x - centerX;

        }

        

    }

  CGPoint point = CGPointMake(proposedContentOffset.x + mindel, 0);

    

    return  point ;

}

@end

/*******分割线*******分割线********分割线*******分割线 *********分割线*********分割线***********/ 

 

//  ViewController.m

//  自定义流水布局

//

//  Created by zyyt on 16/7/20.

//  Copyright © 2016年 sjb. All rights reserved.

//

 

#import "ViewController.h"

#import "SJBFlowLayout.h"

#import "SJBCollectionCell.h"

#import "AFNetworking.h"

 

 

@interface ViewController ()<UICollectionViewDataSource>

 

@property (nonatomic,strong)NSMutableArray * dataSouce;

@property (nonatomic,strong)UICollectionView * collectionView;

 

@end

 

/*******分割线*******分割线********分割线*******分割线 *********分割线*********分割线***********/ 

 

static NSString * const cellID = @"cell";

 

@implementation ViewController

 

- (NSMutableArray *)dataSouce

{

    if (_dataSouce == nil) {

    

        _dataSouce = [NSMutableArray array];

   

    }

    return _dataSouce;

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

    SJBFlowLayout * layout = [[SJBFlowLayout alloc] init];

    layout.itemSize = CGSizeMake(100, 100);

    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 200) collectionViewLayout:layout];

    self.collectionView.dataSource = self;

    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([SJBCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:cellID];

  

    [self.view addSubview:self.collectionView];

    [self requestData];

    }

 

- (void)requestData

{

    NSMutableDictionary * params = [NSMutableDictionary dictionary];

    params[@"a"] =@"list";

    params[@"c"] = @"data";

    params[@"type"] = @(10);

    params[@"page"] = @(0);

 

    

    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];

    

  [manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {

      

      NSLog(@"%@",responseObject);

      

      for (int i=0; i<[responseObject[@"list"] count]; i++) {

          

          [ self.dataSouce addObject:responseObject[@"list"][i]];

          

      }

      

      [self.collectionView reloadData];

      

 

  } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {

      

  }];

    

 

 

}

 

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 1;

}

 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return self.dataSouce.count;

}

 

 

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    SJBCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];

 

    cell.modelDic = [self.dataSouce objectAtIndex:indexPath.item];

   

    cell.contentView.backgroundColor = [UIColor whiteColor];

    

    return cell;

    

}

@end

 

/*******分割线*******分割线********分割线*******分割线 *********分割线*********分割线***********/ 

 

 

#import "SJBCollectionCell.h"

#import "UIImageView+WebCache.h"

#import "UIImage+Circal.h"

 

@interface SJBCollectionCell ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

 

@end

 

@implementation SJBCollectionCell

 

- (void)awakeFromNib {

    // Initialization code

}

 

- (void)setModelDic:(NSDictionary *)modelDic

{

    _modelDic = modelDic;

    

    NSLog(@"%@",modelDic);

    

    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[modelDic objectForKey:@"image1"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

        

        self.imageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

        

    } ];

    self.imageView.contentMode = UIViewContentModeScaleAspectFill;

    

}

 

@end

posted @ 2016-07-20 14:20  sujianbo  阅读(251)  评论(0编辑  收藏  举报