UICollectionView的使用

来源:互联网 发布:如何培养职业道德知乎 编辑:程序博客网 时间:2024/06/06 04:32

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,NSURLConnectionDataDelegate>

@end



ViewController.m

#import "ViewController.h"

#import "MyLayout.h"
#import "MyCell.h"
#import "MyModel.h"
@interface ViewController ()
{
    UICollectionView *_collectionView;
    NSMutableArray *_dataArray;
    NSMutableData *_data;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self prepareData];
    
    [self uiConfig];
    
}

-(void)prepareData
{
    _dataArray = [[NSMutableArray alloc]init];
    _data = [[NSMutableData alloc]init];
//    for (int i = 0; i<30; i++) {
//        MyModel *model = [[MyModel alloc]init];
//        model.cellHeight = 30.0 + (arc4random() % 300) ;
//        [_dataArray addObject:model];
//    }
    NSString *url = @"http://i.snssdk.com/gallery/1/top/?tag=ppmm&offset=1&count=30";
    
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] delegate:self];
}

-(void)uiConfig
{
    MyLayout *layout = [[MyLayout alloc]init];
    layout.images = _dataArray;
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[MyCell class] forCellWithReuseIdentifier:@"cell"];
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
    
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_data setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    id res = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",res);
    NSDictionary *dic = (NSDictionary *)res;
    NSArray *arr = dic[@"data"];
    for (NSDictionary *d in arr) {
        MyModel *model = [[MyModel alloc]init];
        model.imgUrl = d[@"middle_url"];
        model.imgWidth = [d[@"image_width"] floatValue];
        model.imgHeight = [d[@"image_height"] floatValue];
        [_dataArray addObject:model];
        
    }
    //计算高度,用多线程计算
    //这种方法,适用于所有的数组元素之间没有关联的,也没有次序的情况
    //这个方法后面的代码,会在所有的线程执行完成以后再继续执行
    dispatch_apply(_dataArray.count, dispatch_get_global_queue(0, 0), ^(size_t n) {
        MyModel *model = _dataArray[n];
        model.cellHeight = model.imgHeight / model.imgWidth * 160;
    });
    [_collectionView reloadData];
    
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.model = _dataArray[indexPath.row];
    return cell;
}

@end


MyModel.h

#import <Foundation/Foundation.h>

@interface MyModel : NSObject

@property (nonatomic,assign) float cellHeight;

@property (nonatomic,assign) float imgWidth;
@property (nonatomic,assign) float imgHeight;
@property (nonatomic,copy) NSString *imgUrl;


@end


MyModel.m

#import "MyModel.h"

@implementation MyModel

@end


MyCell.h

#import <UIKit/UIKit.h>
#import "MyModel.h"
@interface MyCell : UICollectionViewCell

@property (nonatomic,strong) MyModel *model;


@end


MyCell.m

#import "MyCell.h"
#import "UIImageView+WebCache.h"
@implementation MyCell
{
    UIImageView *_imgv;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self uiConfig];
    }
    return self;
}
-(void)uiConfig
{
    _imgv = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, self.contentView.frame.size.width - 10, self.contentView.frame.size.height - 10)];
    [self.contentView addSubview:_imgv];
}

-(void)setModel:(MyModel *)model
{
    _imgv.frame = CGRectMake(5, 5, self.contentView.frame.size.width - 10, self.contentView.frame.size.height - 10);
    [_imgv setImageWithURL:[NSURL URLWithString:model.imgUrl]];
    _imgv.backgroundColor = [UIColor colorWithRed:0.1*(arc4random()%10) green:0.1*(arc4random()%10) blue:0.1*(arc4random()%10) alpha:1];
}


@end

MyLayOut.h

#import <UIKit/UIKit.h>

@interface MyLayout : UICollectionViewLayout

@property (nonatomic,strong) NSMutableArray *images;

@end

MyLayOut.m

#import "MyLayout.h"
#import "MyModel.h"
@implementation MyLayout

//返回整个collectionView的大小
-(CGSize)collectionViewContentSize
{
    float heightLeft = 0.0;
    float heightRight = 0.0;
    for (int i = 0; i<_images.count; i++) {
        MyModel *model = _images[i];
        float height = model.cellHeight;
        if (heightRight > heightLeft) {
            heightLeft += height;
        }
        else
        {
            heightRight += height;
        }
    }
    return CGSizeMake(320, heightLeft>heightRight?heightLeft:heightRight);
}

//返回对应indexPath的cell的属性
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    float heightLeft = 0.0;
    float heightRight = 0.0;
    for (int i = 0; i<indexPath.row; i++) {
        MyModel *model = _images[i];
        float height = model.cellHeight;
        if (heightRight > heightLeft) {
            heightLeft += height;
            attr.center = CGPointMake(80, heightLeft - height/2);
        }
        else
        {
            heightRight += height;
            attr.center = CGPointMake(240, heightRight - height/2);
        }
        attr.size = CGSizeMake(160, height);
    }
    
    return attr;
}

//返回所有的cell的属性的数组
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    for (int i=0; i<[self.collectionView numberOfItemsInSection:0]; i++) {
        [arr addObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]]];
    }
    return arr;
}


@end



0 0
原创粉丝点击