iOS 自定义colletionView(纯代码)

大家都说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
{
    //--单机事件
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值