iOS 自定义colletionView(纯代码)

来源:互联网 发布:淘宝定制的好不好 编辑:程序博客网 时间:2024/06/07 22:35

大家都说colletionView和UITabbleView 是兄弟,而且colletionView是在IOS 6之后出来的, colletionView和UITabbleView他俩确实是兄弟,但是使用的时你回遇到好多坑。
比如:
UICollectionView *colletionView = [[UICollectionView alloc]init];初始化一个colletionView,如果你这么搞,你就掉到坑里了。应为人家官方文档是这样给你的。这里写图片描述
so!!!!你这样搞就崩掉。你只能这样。

 UICollectionViewFlowLayout *grid =[[UICollectionViewFlowLayout alloc] init]; grid.itemSize = CGSizeMake(80, 80); //设置colletionView的大小grid.sectionInset = UIEdgeInsetsMake(10.0, 10, 10, 10);UICollectionView *colletionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:grid];colletionView.delegate =self; colletionView.dataSource = self;[colletionView registerClass:[photoCell class] forCellWithReuseIdentifier:@"simpleCell"];//这个一定要加不加上的化你的Cell init 是不会调用的哦 !!

OK 正就成功实例化了一个colletionView它与它的兄弟一样需要设置代理,设置数据源。在实例化的时候已经设置好了。
现在去实现他的代理并且自定义一个colletionViewCell
自定义Cell 要去自定义一个Cell类继承UICollectionViewCell
.h

#import <UIKit/UIKit.h>@interface Cell : UICollectionViewCell@property (nonatomic,strong)UIImageView *image;@end

.m

@implementation Cell-(id)initWithFrame:(CGRect)frame{        self = [super initWithFrame:frame];        if (self)        {            // change to our custom selected background view            self.image = [[UIImageView alloc]init];            [self.image setFrame:CGRectMake(self.contentView.frame.size.width/2+20+5, -5, 20, 20)];            [self.image setBackgroundColor:[UIColor redColor]];            self.image.layer.cornerRadius=self.image.frame.size.width/2; // 将图层的边框设置为圆角            self.image.layer.masksToBounds=YES; // 隐藏边界            [self addSubview:self.image];        }        return self;}@end
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{    return 1;}-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{    return 10;}-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{  static NSString *cellIdentifier = @"simpleCell"; Cell *cell = (Cell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];  if (cell ==nil) {   cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];    }    return cell;}- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{    //--单机事件}
1 0
原创粉丝点击