IOS_UICollectionView的使用
UICollectionView是一个很强大的控件,九宫格神马的都是浮云,接下来我们来看下如何用他写一个九宫格出来,
实现的方法有很多种,有storyboard和xib,不过我推荐使用xib,可以随便移植到任何一个项目,
1.新建一个我们的控制器,继承UICollectionViewController
@interface ProductViewControler : UICollectionViewController
@end
1.1自定义cell,这个cell和xib关联,xib的作用就是显示,说白了,cell和xib关联的意思就是,系统自动帮我们生成一些代码加入到我们的cell中,
我们也可以自己写cell,不用xib,但是这比较蛋疼
// // ProductCell.m // colection // // Created by apple on 14-8-1. // Copyright (c) 2014年 pj. All rights reserved. // #import "ProductCell.h" #import "Product.h" @interface ProductCell() @property (weak, nonatomic) IBOutlet UILabel *uiLabel;//这2个属性要和xib关联上 @property (weak, nonatomic) IBOutlet UIImageView *uiIcon; @end @implementation ProductCell - (void)setProduct:(Product *)product { _product = product; self.uiIcon.image = [UIImage imageNamed:_product.icon]; self.uiIcon.layer.cornerRadius = 10;//设置图片的圆圈边距,设置的不是在主layer上,而是第二个layer上 self.uiIcon.layer.masksToBounds = YES;//超出自动裁切,因为imageView有2个layer,所以必须剪切 self.uiLabel.text = _product.title; } @end
2.我们来看看他的常用使用方法
cellsize 宽和高
min spacing 最小间距,forcel 就表示单元格和单元格的间距,for line就表示最小行与行的间距
3.接下来看代码:
// // ProductViewControler.m // colection // // Created by apple on 14-7-19. // Copyright (c) 2014年 pj. All rights reserved. // #import "ProductViewControler.h" #import "Product.h" #import "ProductCell.h" @interface ProductViewControler () @property (nonatomic,strong) NSArray *products; @end @implementation ProductViewControler static NSString *ProductCellID = @"ProductCell2"; - (void)viewDidLoad { [super viewDidLoad];
// 在这里必须注册 UINib *nib = [UINib nibWithNibName:@"Product" bundle:nil]; [self.collectionView registerNib:nib forCellWithReuseIdentifier:ProductCellID]; } - (NSArray *)products { if (_products == nil) { _products = [Product products]; } return _products; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.products.count; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { // UIcollectionViewCell必须提前注册 ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ProductCellID forIndexPath:indexPath]; cell.product = self.products[indexPath.row]; return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { Product *p = self.products[indexPath.row]; NSLog(@"%@",p.title); } @end

浙公网安备 33010602011771号