collectionView技巧

2017-11-29  本文已影响19人  Vijay_

示例

//
//  MyVC.m
//  uicollection
//
//  Created by 杰王 on 2017/11/28.
//  Copyright © 2017年 杰王. All rights reserved.
//

#import "MyVC.h"

@interface MyVC ()<UICollectionViewDelegate>

@end

@implementation MyVC

static NSString * const reuseIdentifier = @"Cell";
- (instancetype)init{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.itemSize = [UIScreen mainScreen].bounds.size;
    
    self = [super initWithCollectionViewLayout:layout];
    return self;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    cell必须要注册 不能自己创建
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.contentInset =  UIEdgeInsetsMake(0, 0, 0, 0);
    self.collectionView.bounces = NO;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



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

    return 4;
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    UIImageView *mv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"guide%liBackground",indexPath.row+1]]];
    mv.frame = cell.bounds ;
    [cell addSubview:mv];
}

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

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.contentView.bounds = self.view.bounds;
    return cell;
}


@end

注意:cell必须要当前控制器注册一个class或者xib 不能自己创建

cell的高宽等布局信息都在布局对象中设置

上一篇 下一篇

猜你喜欢

热点阅读