UICollectionView的实现代码


首先可以先自定义一个cell

@interface CollectionViewCell : UICollectionViewCell

继承自UICollectionViewCell

并添加一个ImageView,用autolaytou固定


193026_xjXE_2370932.png

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


193026_U7VU_2370932.png

确保Class指定正确

193026_YSAs_2370932.png

下面是AUTOLAYOUT

193026_Ess1_2370932.png

记得连线imageView

193026_EzVC_2370932.png

上代码

#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。这里发现地址有三次出现,代表重用了两次

193027_lSAp_2370932.png


转载于:https://my.oschina.net/wupengnash/blog/464300

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值