UICollectionView 类似于 UITableView ,布局更灵活。
//实现三个协议: <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> //创建 UICollectionView - (void)createCollectionView{ UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; //设置对齐方式 [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal]; //cell间距 layout.minimumInteritemSpacing = 5.0f; //cell行距 layout.minimumLineSpacing = 1.0f; //collectionViewLunBo = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, 320, 200)]; //需要layout 否则崩溃:UICollectionView must be initialized with a non-nil layout parameter collectionViewLunBo = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 20, 320, 300) collectionViewLayout:layout]; collectionViewLunBo.dataSource = self; collectionViewLunBo.delegate = self; collectionViewLunBo.pagingEnabled = YES; collectionViewLunBo.backgroundColor = [UIColor yellowColor]; [self.view addSubview:collectionViewLunBo]; //注册Cell类,否则崩溃: must register a nib or a class for the identifier or connect a prototype cell in a storyboard [collectionViewLunBo registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"]; } //required -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ //[collectionViewLunBo registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionViewCell"]; static NSString *cellIDa = @"MyCollectionViewCell"; collectionCell = (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIDa forIndexPath:indexPath]; collectionCell.backgroundColor = [UIColor blueColor]; //collectionCell.imageView.image = [UIImage imageNamed:@""]; return collectionCell; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return 4; } //optional - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"%@",indexPath); UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath]; cell.backgroundColor = [UIColor whiteColor]; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ return CGSizeMake(310, 300); } - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ return UIEdgeInsetsMake(5, 5, 5, 5);// top left bottom right Cell边界范围 }
原文:http://my.oschina.net/liuchuanfeng/blog/404901