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

通过Xib创建 UICollectionView 和自定义UICollectionViewCell

时间:2016-04-03 18:47:06      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

1。在控制器的viewDidLoad方法中添加代码

CGFloat itemWidth = (kScreenW - kSpacingW * 3) / 2;

    NSLog(@"itemWidth == %f",itemWidth);

    CGFloat itemHeight = itemWidth * 0.75 + 71;

    NSLog(@"itemWidth == %f",itemHeight);

 

    

    UICollectionViewFlowLayout*layout = [[UICollectionViewFlowLayout alloc]init];

    layout.itemSize = CGSizeMake(itemWidth, itemHeight);

    layout.minimumInteritemSpacing = kSpacingW;

    layout.minimumLineSpacing = kSpacingW;

    layout.sectionInset = UIEdgeInsetsMake(0, kSpacingW, 0, kSpacingW);

    

    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];

    [self.view addSubview:self.collectionView];

    self.collectionView.dataSource = self;

    self.collectionView.delegate = self;

    self.collectionView.backgroundColor = [UIColor whiteColor];

    [self.collectionView registerClass:[HotCell class] forCellWithReuseIdentifier:@"HotCell"];

 

2.实现collectionView的代理方法

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

{

    return 10;

}

 

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

{

    HotCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotCell" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor whiteColor];

    return cell;

}

3.通过XIB自定义cell

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        

        // 初始化时加载collectionCell.xib文件

        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"HotCell" owner:self options:nil];

        

        // 如果路径不存在,return nil

        if (arrayOfViews.count < 1) {

            return nil;

        }

        // 如果xib中view不属于UICollectionViewCell类,return nil

        if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {

            return nil;

        }

        // 加载nib

        self = [arrayOfViews objectAtIndex:0];

        

    }

    

    return self;

}

通过Xib创建 UICollectionView 和自定义UICollectionViewCell

标签:

原文地址:http://www.cnblogs.com/fantasy3588/p/5350230.html

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