UICollectionView的使用和布局方法

来源:互联网 发布:属下知罪by枯目书包网 编辑:程序博客网 时间:2024/05/19 12:25
#import "ViewController.h"#import "CustomCollectionViewCell.h"@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>@end@implementation ViewController- (void)dealloc {    [super dealloc];}- (void)viewDidLoad {    [super viewDidLoad];    //    流式布局    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];    //    滑动方向    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;    //    item的大小    flowlayout.itemSize = CGSizeMake(120, 150);    //    item的最小行间距    flowlayout.minimumLineSpacing = 5;   //    item的最小列间距    flowlayout.minimumInteritemSpacing = 5;
//    collection的核心就是layout, 负责item的大小和位置    UICollectionView *collectView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];    collectView.backgroundColor = [UIColor whiteColor];    collectView.delegate = self;    collectView.dataSource = self;//    切记,一定要注册重用池    [collectView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"CustomCollectionViewCellIdentifier"];    [self.view addSubview:collectView];    [collectView release];    }//UICollectionView被选中时调用的方法  -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {          NSLog(@"item======%d",indexPath.item);      NSLog(@"row=======%d",indexPath.row);      NSLog(@"section===%d",indexPath.section);  }  
<pre name="code" class="objc">//返回item的个数 (方法必须实现)- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 100;}


//cell上显示的内容 (方法必须实现)- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {        CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCollectionViewCellIdentifier" forIndexPath:indexPath];    cell.label.text = @"天马行空";    return cell;}
//定义展示的Section的个数  -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView  {      return 2;  }  



1 1