zoukankan      html  css  js  c++  java
  • 通过Xib创建 UICollectionView 和自定义UICollectionViewCell

    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;

    }

    1
  • 相关阅读:
    Golang网络编程-套接字(socket)篇
    Golang并发编程-传统的同步工具"锁"实战篇
    Golang并发编程-select实战篇
    Golang并发编程-channel实战篇
    Golang并发编程-Go程(Goroutine)实战篇
    Jenkins实现简单流程部署代码
    Jenkins权限管理
    Jenkins插件管理篇
    Jenkins部署实战案例
    Golang常见的字符串函数操作实战篇
  • 原文地址:https://www.cnblogs.com/fantasy3588/p/5350230.html
Copyright © 2011-2022 走看看