`

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);
}

 

  • 大小: 42.9 KB
分享到:
评论
2 楼 yanransysu 2014-11-03  
为啥结果没有显示图片嘞,我都已经把你共享的文件给放进去了?
1 楼 如果宅 2014-08-15  
附件下载下来是图片!

相关推荐

Global site tag (gtag.js) - Google Analytics