代码如下

PureLayout

.h文件,那里大致的直白传送了数据源

@interface PureLayout : UICollectionViewLayout

@property(nonatomic,strong)NSArray *dataArray;//数据源
@property(nonatomic,assign) NSInteger maxCount;//列数
@end

.m文件 定义必要展示的列数,水平 垂直间隔等主导音信

#import "PureLayout.h"
#import "PicModel.h"

static CGFloat horizonalSpace = 10;//水平间隔
static CGFloat verticalSpace = 15;//垂直间隔

@interface PureLayout ()
@property(nonatomic,strong) NSMutableArray *offSets;//用于存储不同列的MAXY信息
@end

@implementation PureLayout

-(void)prepareLayout{

    _maxCount = MAXCOUNT;
}

基于必要出示的列数,使用数组分别记录每行所在列item的frame.origin.y,举行对照,设置UICollectionView的contentsize

-(CGSize)collectionViewContentSize{

    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = 0.0;

   _offSets = [NSMutableArray array];

    for (int i =0; i<_maxCount; i++) {
        [_offSets addObject:@0];
    }

    for (int i = 0; i<self.dataArray.count; i++) {
        NSInteger col = i % _maxCount;
        PicModel *model = self.dataArray[i];

        CGFloat offSetY ;
        offSetY = [_offSets[col] floatValue] + model.rowHeight + verticalSpace;
        _offSets[col] = @(offSetY);
        height = MAX(height, offSetY);
    }

    if (height < [UIScreen mainScreen].bounds.size.height) {
        height = [UIScreen mainScreen].bounds.size.height;
    }
    return CGSizeMake(width, height);
}

回来可知Rect内的元素的attributes信息

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

    NSMutableArray * attributes = [NSMutableArray array];
    for (int i =0 ; i<self.dataArray.count; i++) {
        UICollectionViewLayoutAttributes *attribute = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        [attributes addObject:attribute];
    }
    return attributes;
}

对不相同的indexpath的items设置attributes音讯

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    PicModel *model = self.dataArray[indexPath.row];
    CGFloat itemWidth = ([UIScreen mainScreen].bounds.size.width - (MAXCOUNT - 1) * 10)/_maxCount;
    attribute.size = CGSizeMake(itemWidth, model.rowHeight);
    CGFloat itemY = 0.0;
    CGFloat itemX = 0.0;

    NSInteger col = indexPath.row % _maxCount;
    itemX = (([UIScreen mainScreen].bounds.size.width - (MAXCOUNT - 1) * 10)/_maxCount + horizonalSpace)* col;
    if (indexPath.row <_maxCount) {
        itemY = 0.0;
    }else{
        UICollectionViewLayoutAttributes *otherAttribute = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row - _maxCount inSection:0]];
        itemY = CGRectGetMaxY(otherAttribute.frame) + verticalSpace;
    }

    attribute.frame = CGRectMake(itemX, itemY, itemWidth,  model.rowHeight);
    return attribute;
}

最终添加上该办法,边界改变是重复布局

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{

    return YES;
}

只是一个简约的额瀑布流demo,还有蛮多地方需求优化,这里仅仅写下局地基本思路。

官方给出的几个demo很有学习价值,CircleLayout以及LinLayout,在自己之前的交由的参照链接里面都是可以向来下载的,对于与作品中的CircleLayout用法,insert和delete方法已经被appearing和disappearing取代了,参考的githubdemo被我fork了一份,可以实行下载学习
https://github.com/w467364316/CircleLayout.git

 

http://www.bkjia.com/IOSjc/985818.htmlwww.bkjia.comtruehttp://www.bkjia.com/IOSjc/985818.htmlTechArticleios UICollectionView的采取UICollectionView的施用有二种方法,一种是继承UICollectionViewController,那么些Controller会自带一个UICollectionView;其它一种是…

自定义一个UICollectionViewLayout

继承自UICollectionViewLayout类,然后一般要求重载下列方式:

  • -(void)prepareLayout;

  • 每一遍请求布局时候都会活动调用,可以在那里修改部分少不了的layout的构造和起来必要的参数等

  • -(CGSize)collectionViewContentSize;

  • 定义UIcollectionView的ContentSize,内容大小

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

  • 归来可见区域rect内的具有因素的布局音信

  • 回到包涵attributes的数组

  • -(UICollectionViewLayoutAttributes
    *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;

  • 概念每个indexpath的item的布局信息

  • 相应的还有定义supplement以及decoration的点子 那里就不在进行罗列

  • -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;

  • 当边界爆发变动时,是还是不是相应刷新布局。倘使YES则在分界变化(一般是scroll到其余地点)时,将再一次计算必要的布局音讯。

    demo

demo地址

Simulator Screen Shot 2016年10月13日 上午10.52.12.png

行使了一组图片和一个json文件(如若添加过后发现解析为空,在target
->Build Phase – >copy Bundle Resource添加需求的json文件)
正在减肥用的都是减肥励志的哈哈

ios UICollectionView的使用

UICollectionView的施用有三种方法,一种是继承UICollectionViewController,这些Controller会自带一个UICollectionView;其它一种是当做一个视图放在普通的UIViewController里面。

个体更欣赏第二种。上边选用第三种艺术容易介绍一下UICollectionView的选用。

1.UIViewController兑现委托,代码如下

@interface YourViewController : UIViewController

2.申明UICollectionView,代码如下

@property(nonatomic,retain)UICollectionView*myCollectionView;

3.初步化UICollectionView,代码如下

– (void)viewDidLoad
{
[super viewDidLoad];
[self initConllectionView];
}
-(void)initConllectionView{
CircleLayout*layout=[[CircleLayout alloc] init];
myCollectionView=[[UICollectionView alloc]
initWithFrame:self.view.bounds collectionViewLayout:layout];
[myCollectionView registerClass:[UICollectionViewCell class]
forCellWithReuseIdentifier:@”cell”];
myCollectionView.backgroundColor=[UIColor whiteColor];
myCollectionView.delegate=self;
myCollectionView.dataSource=self;
[self.view addSubview:myCollectionView];
[layout release];
}

那其中的CircleLayout继承自UICollectionViewLayout,主要用来彰显UICollectionView的布局以及一些性质。

4.实现- (UICollectionViewCell *)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

-(UICollectionViewCell*)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell*cell=[collectionView
dequeueReusableCellWithReuseIdentifier:CELL_STR
forIndexPath:indexPath];
for (UIView*view in cell.contentView.subviews) {
if (view) {
[view removeFromSuperview];
}
}
UIImageView*imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0,
0, ITEM_WIDTH, ITEM_WIDTH)];
if (indexPath.row>4) {
imgView.image=[UIImage imageNamed:@”apple.png”];
}else{
imgView.image=[UIImage imageNamed:@”applec.png”];
}
[cell.contentView addSubview:imgView];
[imgView release];
return cell;
}

5.cell的大小

-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(130,130);
}

 

CircleLayout的代码:

CircleLayout.h

#import
#import
@interface CircleLayout : UICollectionViewLayout
@property (nonatomic, assign) CGPoint center;
@property (nonatomic, assign) CGFloat radius;
@property (nonatomic, assign) NSInteger cellCount;
@end

 

CircleLayout.m

 

#define ITEM_SIZE 130
#import “CircleLayout.h”

@implementation CircleLayout
@synthesize cellCount,center,radius;

  • (void)prepareLayout{
    [super prepareLayout];
    CGSize size = self.collectionView.frame.size;
    cellCount=[self.collectionView numberOfItemsInSection:0];
    center=CGPointMake(size.width/2, size.height/2);
    radius = MIN(size.width, size.height) / 2.5;
    }
    -(CGSize)collectionViewContentSize{
    return [self collectionView].frame.size;
    }
  • (UICollectionViewLayoutAttributes
    *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path
    {
    UICollectionViewLayoutAttributes* attributes =
    [UICollectionViewLayoutAttributes
    layoutAttributesForCellWithIndexPath:path];
    attributes.size = CGSizeMake(ITEM_SIZE, ITEM_SIZE);
    attributes.center = CGPointMake(center.x + radius * cosf(2 * path.item
    * M_PI /cellCount),

center.y + radius * sinf(2 * path.item * M_PI /cellCount));
return attributes;
}
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{
NSMutableArray* attributes = [NSMutableArray array];
for (NSInteger i=0 ; i < self.cellCount; i++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForItem:i
inSection:0];
[attributes addObject:[self
layoutAttributesForItemAtIndexPath:indexPath]];
}
return attributes;
}

  • (UICollectionViewLayoutAttributes
    *)initialLayoutAttributesForInsertedItemAtIndexPath:(NSIndexPath
    *)itemIndexPath{
    UICollectionViewLayoutAttributes* attributes = [self
    layoutAttributesForItemAtIndexPath:itemIndexPath];
    attributes.alpha = 0.0;
    attributes.center = CGPointMake(center.x, center.y);
    return attributes;
    }
  • (UICollectionViewLayoutAttributes
    *)finalLayoutAttributesForDeletedItemAtIndexPath:(NSIndexPath
    *)itemIndexPath
    {
    UICollectionViewLayoutAttributes* attributes = [self
    layoutAttributesForItemAtIndexPath:itemIndexPath];
    attributes.alpha = 0.0;
    attributes.center = CGPointMake(center.x, center.y);
    attributes.transform3D = CATransform3DMakeScale(0.1, 0.1, 1.0);
    return attributes;
    }
    @end

UICollectionViewLayoutAttrubutes

一个很首要的类重点记录了cells,supplementaryViews,decorationviews的职位,size,透明度,层级等

  • @property (nonatomic) CGRect frame; frame信息
  • @property (nonatomic) CGPoint center; 中心点
  • @property (nonatomic) CGSize size;大小
  • @property (nonatomic) CATransform3D transform3D;
  • @property (nonatomic) CGRect bounds NS_AVAILABLE_IOS(7_0);
  • @property (nonatomic) CGAffineTransform transform
    NS_AVAILABLE_IOS(7_0);
  • @property (nonatomic) CGFloat alpha;透明度
  • @property (nonatomic) NSInteger zIndex; // default is 0 层级
  • @property (nonatomic, getter=isHidden) BOOL hidden; // As an
    optimization, UICollectionView might not create a view for items
    whose hidden attribute is YES
  • @property (nonatomic, strong) NSIndexPath *indexPath;位置
  • @property (nonatomic, readonly) UICollectionElementCategory
    representedElementCategory;
  • @property (nonatomic, readonly, nullable) NSString
    *representedElementKind; 响应类型(区分cell,supple,decaration)
    那就是说当UICollectionView获取布局的时候会透过访问每个地方的构件通过其attribute来精晓其布局音信

PickModel

应用到的model
.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface PicModel : NSObject
@property(nonatomic,strong) NSString *picPath;//图像
@property(nonatomic,strong) NSString *picDetail;//详细内容
@property(nonatomic,assign) CGFloat rowHeight;//行高

+(instancetype)initWithDic:(NSDictionary*)dic;
-(instancetype)initWithDic:(NSDictionary*)dic;

@end

.m
通过detail总结中度,总计所在item的莫大,那里图片的莫大直接约束限制死了,可以改为按百分比统计等。

#import "PicModel.h"

@implementation PicModel

+(instancetype)initWithDic:(NSDictionary*)dic{

    PicModel *model = [self alloc];
    return [model initWithDic:dic];
}

-(instancetype)initWithDic:(NSDictionary*)dic{

    if (self = [super init]) {
        self.picPath = dic[@"path"];
        self.picDetail = dic[@"detail"];

        CGFloat width = ([UIScreen mainScreen].bounds.size.width -(MAXCOUNT - 1) * 10)/MAXCOUNT;
        CGSize size = [dic[@"detail"] boundingRectWithSize:CGSizeMake(([UIScreen mainScreen].bounds.size.width -(MAXCOUNT - 1) * 10)/MAXCOUNT, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
        self.rowHeight = size.height + 59 *width / 100 ;
    }
    return self;
}
@end

透过修改定义的列数

Pch文件.png

ViewController

.m文件

#import "BaseViewController.h"
#import "PicModel.h"
#import "PureLayout.h"
#import "PureCollectionViewCell.h"

@interface BaseViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong) UICollectionView *mainCollectionView;
@property(nonatomic,strong) NSMutableArray *dataArray;//数据源数组
@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.dataArray = [NSMutableArray array];
    //解析geojson文件
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Detail" ofType:@"geojson"];
    NSArray *detailArr = [[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:jsonPath] options:NSJSONReadingMutableContainers error:nil] objectForKey:@"data"
    ];

    //处理model数据
    for (int i =0; i<12; i++) {
        NSString *path = [NSString stringWithFormat:@"%d.jpg",i];
        PicModel *model = [PicModel initWithDic:[NSDictionary dictionaryWithObjectsAndKeys:path,@"path",detailArr[i],@"detail", nil]];
        [self.dataArray addObject:model];
    }

    [self definationMainCollectionView];

    //添加MJRefreshFooter 添加数据
    __weak typeof(self)weakSelf = self;
    self.mainCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        for (int i =0; i<12; i++) {
            NSString *path = [NSString stringWithFormat:@"%d.jpg",i];
            PicModel *model = [PicModel initWithDic:[NSDictionary dictionaryWithObjectsAndKeys:path,@"path",detailArr[i],@"detail", nil]];
            [weakSelf.dataArray addObject:model];
        }
        [weakSelf.mainCollectionView reloadData];
        [weakSelf.mainCollectionView.mj_footer endRefreshing];
    }];
}

/**
 *  设置相关UICollectionView信息
 */
-(void)definationMainCollectionView{

    PureLayout *layout = [[PureLayout alloc] init];
    layout.dataArray = self.dataArray;

    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
    [self.mainCollectionView registerNib:[UINib nibWithNibName:@"PureCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"pureCell"];
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    self.mainCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mainCollectionView];
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 1;
}

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

   return  self.dataArray.count;
}

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

    PureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pureCell" forIndexPath:indexPath];
    PicModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

对此急需拔取到列表的页面,一般是应用UITableView或者是UICollectionView来兑现。一贯以来都是一向利用UICollectionViewFlowLayout,基本都能完毕须要功效,不过对于直接接纳UICollectionViewLayout来自定义view的layout没怎么使用过,那里查了蛮多材料自己写了demo,仅供日后参考了。
参考资料地址:
http://blog.csdn.net/majiakun1/article/details/17204921
http://www.cnblogs.com/wangyingblock/p/5627448.html

相关文章