• 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;

    }

  • 相关阅读:
    如何添加和删除本地存储中的数据?
    本地存储和cookies之间的区别是什么?
    那么如何使用WebSQL?
    WebSQL是HTML 5规范的一部分吗?
    WebSQL是什么?
    什么是本地存储的生命周期?
    本地存储和cookies之间的区别是什么?
    什么是多线程中的上下文切换?
    web workers是什么,为什么我们需要web workers?
    连接点?
  • 原文地址:https://www.cnblogs.com/oumygade/p/4571768.html
Copyright © 2020-2023  润新知