XIB拖一个ColletionView到界面中,
#import "ColletionViewController.h"
@interface ColletionViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (strong, nonatomic) IBOutlet UICollectionView *tryCollectionView;
@end
@implementation ColletionViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//注册
[_tryCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
//滚动方向
UICollectionViewFlowLayout * flowLayOut = [[UICollectionViewFlowLayout alloc] init];
[flowLayOut setScrollDirection:UICollectionViewScrollDirectionVertical];
_tryCollectionView.collectionViewLayout = flowLayOut;
_tryCollectionView.delegate = self;
_tryCollectionView.dataSource = self;
}
#pragma mark - <UICollectionViewDataSource,UICollectionViewDelegate>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 10;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellId = @"UICollectionViewCell";
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
UIImageView * collectionImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
collectionImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"头像%ld.jpg",(long)indexPath.row + 1]];
[cell.contentView addSubview:collectionImageView];
return cell;
}
//每个items的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(100, 100);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(5, 5, 5, 5);
}
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//临时改变个颜色,看好,只是临时改变的。如果要永久改变,可以先改数据源,然后在cellForItemAtIndexPath中控制。(和UITableView差不多吧!O(∩_∩)O~)
cell.backgroundColor = [UIColor greenColor];
NSLog(@"item======%ld",(long)indexPath.item);
NSLog(@"row=======%ld",(long)indexPath.row);
NSLog(@"section===%ld",(long)indexPath.section);
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
@end
XIB布局图,