zoukankan      html  css  js  c++  java
  • iOS UICollectionView的使用(用代码创建UI)

    在控制器中添加CollectionView

    在控制器的viewDidLoad方法中初始化CollectionView

    static NSString *ID = @"collectionViewCell";

    - (void)viewDidLoad {

        [super viewDidLoad];

        //    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds];   这种初始化方法,无法编译通过

        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]];  //  这里不要用UICollectionViewLayout,UICollectionViewLayout是抽象基类,是专门用于子类继承的; UICollectionViewFlowLayout是最基本的布局

        collectionView.dataSource = self;

        collectionView.delegate = self;

        [self.view addSubview:collectionView];

      // 一般都会自定义一个CollectionViewCell,因为系统预制的CollectionViewCell,不像tableViewCell那样有Label,ImageView,CollectionViewCell只有2个View:backgroundView和selectedBackgroundView

        [collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:ID];

    }

    #pragma mark - collectionViewDataSource

    - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

    {

        return 1; // 和tableView一样

    }

     

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

    {

        return self.photos.count; // 和tableView一样

    }

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

    {

        CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

        // 不需要再写 if (!cell) {  初始化cell; }

       // indexPath.row 也行,可能collectionView布局更自由,不像tableView那样一般都是“行”,所以更多人喜欢用indexPath.item吧

        [cell.imageV setImage:[UIImage imageNamed:self.photos[indexPath.item]]];

        return cell;

    }

    自定义CollectionViewCell

    // CustomCell.h

    @interface CustomCell : UICollectionViewCell

    @property (nonatomic, weak) UIImageView *imageV;

    @end

    // CustomCell.m

    - (id)initWithFrame:(CGRect)frame

    {

        self = [super initWithFrame:frame];

        if (self) {

            UIImageView *imageView = [[UIImageView alloc]init];

            imageView.frame = CGRectMake(5, 5, 40, 40);

            [self addSubview:imageView];

            _imageV = imageView;

        }

        return self;

    }

  • 相关阅读:
    带符号数的移位
    day03-Java语言基础之运算符
    day02Java语言基础数量部分
    day01Java概述
    交换机光口识别与连接问题
    wireshark怎么抓包
    Java中的语句
    构建主键批注的方法
    通过反射,获得数据库增删改查的sql语句的方法
    sql语句
  • 原文地址:https://www.cnblogs.com/oumygade/p/4571768.html
Copyright © 2011-2022 走看看