码迷,mamicode.com
首页 > 其他好文 > 详细

UICollectionView的实现代码

时间:2015-06-08 20:00:30      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:


首先可以先自定义一个cell

@interface CollectionViewCell : UICollectionViewCell

继承自UICollectionViewCell

并添加一个ImageView,用autolaytou固定


技术分享

记得一定要在这里指定cell的可重用标示符,位置要对,并且和代码里面设置的ID内容一致


技术分享

确保Class指定正确

技术分享

下面是AUTOLAYOUT

技术分享

记得连线imageView

技术分享

上代码

#import "ViewController.h"
#import "CollectionViewCell.h"
@interface ViewController () <UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,strong) NSMutableArray *images;
@property (nonatomic,strong) UICollectionView *ucv;
@end
@implementation ViewController
static NSString *const ID = @"cell";//static 代表外部不能访问,意义上的完全私有(防止extern),const表示ID无法被更改。
-(NSMutableArray *)images
{//image数组的懒加载,将每个图片的名称放到数组里面
    if (!_images) {
        _images = [NSMutableArray array];
        for (int i = 1 ; i <= 20; i++) {
            
            NSString *imageName = [NSString stringWithFormat:@"%d",i];
            [_images addObject:imageName];
        }
        
    }
    return  _images;
}
-(UICollectionView *)ucv
{//懒加载一个UICollectionView 并且设置流水效果,
    if (!_ucv) {
        UICollectionViewFlowLayout *flowv = [[UICollectionViewFlowLayout alloc ] init];
        _ucv = [[UICollectionView alloc ] initWithFrame:CGRectMake(0, 20, 320, 80) collectionViewLayout:flowv];
        
    }
    return _ucv;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //设置代理和数据源
    self.ucv.dataSource = self;
    self.ucv.delegate = self;
    //和tablview不同的是要先注册cell 的nib及可充用标示符
    [self.ucv registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:ID];
    [self.view addSubview:self.ucv];//添加到主视图咯
    
}
#pragma mark - UICollectionView的代理方法,REquired
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  19;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //使用自定义的cell在collectionView中查找可充用的cell
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    //设置cell的图片内容,也可以重写CollectionViewCell 的setImageName方法(定义一个copy的NSString)
    cell.ImageView.image = [UIImage imageNamed:self.images[indexPath.item]];
    NSLog(@"%p",cell);
    return cell;
}
@end


验证是否重用cell,可以打印cell的地址,在终端find地址0x7fdda2e86820。这里发现地址有三次出现,代表重用了两次

技术分享


UICollectionView的实现代码

标签:

原文地址:http://my.oschina.net/wupengnash/blog/464300

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!