UICollectionView使用

来源:互联网 发布:淘宝助手安卓版 编辑:程序博客网 时间:2024/06/05 05:44

一、Storyboard的准备
1.在storyboard的ViewControll拖一个CollectionView
2.在collectionViewCell中添加ImageView和Label
添加Collection
3.创建一个UICollectionViewCell的类,并跟上面的collectionCell绑定
这里写图片描述
4.连线dataSource和delegate,并创建映射
imageView 、titleLabel
这里写图片描述
二、代码:
1.

   //创建一个可变数组    self.dataMArr = [NSMutableArray array];    //创建9张图显示,并加其对应的titleLabel加入字典    for (NSInteger index = 0; index < 9; index++) {        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld", (long)index+1]];        NSString *title = [NSString stringWithFormat:@"{0,%ld}",(long)index+1];        NSDictionary *dic = @{@"image": image, @"title": title};        [self.dataMArr addObject:dic];    } /**记得要遵从协议UICollectionViewDelegate, UICollectionViewDataSource */    self.myCollection.delegate = self;    self.myCollection.dataSource = self;

2.在.m文件中实现代理方法
//collectionView item的个数

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {    return self.dataMArr.count;}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {    //myCollectionCell 这个CellID需要在storyboard那里对应添加相同的,如图三    static NSString *collectionCellID = @"myCollectionCell";    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID forIndexPath:indexPath];    NSDictionary *dic = self.dataMArr[indexPath.row];    UIImage *image = dic[@"image"];    NSString *title = dic[@"title"];    cell.imageView.image = image;    cell.titleLabel.text = title;    return cell;}

这里写图片描述
图三

0 0
原创粉丝点击