IOS学习之 -- UICollectionView

1、实现代理

#import 

@interface ViewController : UIViewController

@end

2、声明UICollectionView

@property (nonatomic, strong) UICollectionView *myCollectionView;

3、实现代理方法

/**
  *数据源代理
  */
//返回个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return 50;
}

//返回单元格,自定义单元格很重要的部分
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cid forIndexPath:indexPath];
    cell.backgroundColor = [UIColor orangeColor];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    imageView.image = [UIImage imageNamed:@"image.jpg"];
    [cell.contentView addSubview:imageView];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 35, 100, 40)];
    label.text = @"路飞";
    label.textColor = [UIColor whiteColor];
    [cell.contentView addSubview:label];

    return cell;
}

 /**
  *布局代理
  */
//设置边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置item宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    return CGSizeMake(self.myCollectionView.bounds.size.width, 80);
}

//选择item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    NSLog(@"选中了---> %lu", indexPath.row);
}

//点击后的item
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor orangeColor];
}

4、绑定View

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.
    //布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //创建CollectionView
    self.myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(20, 30, self.view.bounds.size.width-40, self.view.bounds.size.height-60) collectionViewLayout:flowLayout];

    //注册Cell单元
    [self.myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cid];

    self.myCollectionView.dataSource = self;
    self.myCollectionView.delegate = self;
    self.myCollectionView.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.myCollectionView];
}

你可能感兴趣的:(IOS学习之 -- UICollectionView)