IOS之集合视图UICollectionView

        实现效果如下。


 

1.往ViewController添加UICollectionView,并绑定Delegate和DataSource。

2.新建单元类BookCell,继承UICollectionViewCell

 

BookCell.h

 

#import <UIKit/UIKit.h>

@interface BookCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;//自定义单元控件1
@property (weak, nonatomic) IBOutlet UILabel *label;//自定义单元控件2
@end

 BookCell.m

#import "BookCell.h"

@implementation BookCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

@end

 3.在Interface Builder中设置UICollectionView的Cell的class为BookCell.选中设计界面的单元格,(1)把连线连接到左边View Controller Scene的UICollectionView的Cell的UIImageView,在弹出的菜当中选择imageView(即对应BookCell的imageView变量)(2)把连线连接到左边View Controller Scene的UICollectionView的Cell的UILabel,在弹出的菜当中选择label(即对应BookCell的label变量)(3)选中UICollectionView的Cell,将identifier设置为bookCell(下面第5步会有说明)

 4.设置UICollectionView的数据源初始化。user_head.plist以及图片请见附件。

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self initCollectionView];
}

-(void)initCollectionView{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *plistPath = [bundle pathForResource:@"user_head" ofType:@"plist"];
    dataArr = [[NSArray alloc] initWithContentsOfFile:plistPath];//dataArr为.h文件定义的变量
    NSLog(@"data count = %d",[dataArr count]);
}

 5.将数据源绑定到UICollectionView

 

//显示多少行
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
//显示多少列
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 2;
}
//为每个单元设置UI
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BookCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bookCell" forIndexPath:indexPath];//"bookCell" 对应第三步的cell的identifier
    NSDictionary *dict = [dataArr objectAtIndex:(indexPath.section*2+indexPath.row)];//2为每行的个数
    cell.label.text = [dict objectForKey:@"itemName"];
    NSLog(@"itemName= %@",[dict objectForKey:@"itemName"]);
    cell.imageView.image = [UIImage imageNamed:[dict objectForKey:@"itemImagePath"]];
    return cell;
}

 

 6.添加选择单元格之后的触发事件。

//选择单元格触发事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = [dataArr objectAtIndex:(indexPath.section*2+indexPath.row)];//2为每行的个数
    NSString *userName = [dict objectForKey:@"itemName"];
    NSString *userHead = [dict objectForKey:@"itemImagePath"];
    NSLog(@"userName = %@, userHead = %@", userName,userHead);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值