如果是简单实用UICollectionView的话,用法和UITableView基本一致。下面是用UICollectionView实现的简单图片显示
(1)打开storyboard,将一个UICollectionView拖到View Controller Scene中,默认的UICollectionView已经包含了一个UICollectionViewcell,将一个UIImageView和UILabel拖到UICollectionViewcell中,如下图:
(2)连接输出口datasource和delegate:打开Connections Inspector(option+command+6),从输出口atasource和delegate分别拖曳到ViewController对像中。
(3)在ViewController中实现UICollectionViewDataSource,UICollectionViewDelegate代理
ViewController.h文件如下:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
@end
(4)新建AUICollectionViewCell类,继承UICollectionViewCell,完善.h文件,并连接输出口
AUICollectionViewCell.h如下:
#import <UIKit/UIKit.h>
@interface ACollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *image;
@property (weak, nonatomic) IBOutlet UILabel *title;
@end
(5)完善ViewController.m文件,注释写的比较清楚了
#import "ViewController.h"
#import "ACollectionViewCell.h"
int const cellCount = 40;
@interface ViewController ()
@property(nonatomic,strong)NSArray *imgArr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//图片懒加载
-(NSArray*)imgArr{
if (!_imgArr) {
NSMutableArray *muArr = [NSMutableArray array];
for (int i = 0; i < cellCount; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]];
[muArr addObject:image];
}
_imgArr = muArr;
}
return _imgArr;
}
#pragma mark - UICollectionViewDataSource Delegate
#pragma mark cell的数量
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return cellCount;
}
#pragma mark cell的视图
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"CollectionViewCell";
ACollectionViewCell *collectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
collectionViewCell.layer.cornerRadius = 6.0f;
collectionViewCell.image.image = [self.imgArr objectAtIndex:indexPath.row];
collectionViewCell.title.text = [[NSString alloc] initWithFormat:@"图片%d",indexPath.row];
return collectionViewCell;
}
#pragma mark cell的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(150, 150);
}
#pragma mark cell的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"点击图片%d",indexPath.row);
}
@end
本文Demo下载地址:http://download.csdn.net/detail/dolacmeng/8677213
使用UICollectionView实现Gallery图片浏览效果:http://blog.csdn.net/dolacmeng/article/details/45588293
使用UICollectionView实现瀑布流效果:http://blog.csdn.net/dolacmeng/article/details/45599069