您的位置:首页 > 产品设计 > UI/UE

UICollectionView-数据源

2013-12-13 16:40 387 查看
1。<UICollectionViewDataSource> 数据源
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView //有多少个section,默认为1
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section //每个section内有多少项,即多少个cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath //cell内容
2。注册可复用的 cell
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier //注册 cellClass(可以是标准的cell,也可以是自定义的cell)
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier //注册.xib

e.g. UINib *nib = [UINib nibWithNibName: NSStringFromClass([MyCollectionViewCell class]) bundle:[NSBundle mainBundle]];

[self.collectionView registerNib:nib forCellWithReuseIdentifier:kCollectionViewCellIdentifier];
@implementation MyCollectionViewCell

- (void) awakeFromNib{

[super awakeFromNib]; //load nib的时候做一些初始化工作

self.imageView.backgroundColor = [UIColor clearColor]; //必须先设置单元格内顶级层的view(如单元格内添加了imgView等)的背景色为clear,才能真正体现选中单元格的背景色

self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.bounds];

self.selectedBackgroundView.backgroundColor = [UIColor blueColor];

}

@end
e.g.
UICollectionViewController :
static NSString *kCollectionViewCellId = @"Cells";
- (instancetype) initWithCollectionViewLayout:(UICollectionViewLayout *)layout{

self = [super initWithCollectionViewLayout:layout];

if (self != nil){

[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier :kCollectionViewCellId]; //注册可复用的cell,同UITableView,这里也可以是自定义的collectionViewCell

}

return self;

}

- (void) viewDidLoad{

[super viewDidLoad];

self.collectionView.backgroundColor = [UIColor whiteColor];

}

- (NSInteger)numberOfSectionsInCollectionView :(UICollectionView *)collectionView{

return [self arySectionsSource count ];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

return 3 + arc4random_uniform(5); // 随机数 arc4random_uniform(num) // [ 0 , num )

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
// indexPath : indexPath.section , indexPath.row

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier :kCollectionViewCellIdentifier forIndexPath:indexPath];

。。。。。//设置cell内容

return cell;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: