UICollectionView 在創建的時候,要給它一個UICollectionViewFlowLayout (不然會崩潰),就像tableview一樣,也要為它註冊自定義的cell。 UICollectionViewFlowLayout *flowLayout = [[UICollectionV
UICollectionView 在創建的時候,要給它一個UICollectionViewFlowLayout (不然會崩潰),就像tableview一樣,也要為它註冊自定義的cell。
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init]; [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical]; //cell間距 flowLayout.minimumInteritemSpacing = 10.0f; //cell行距 flowLayout.minimumLineSpacing = 20.0f; //1.添加FlowLayout UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, 320, [UIScreen mainScreen].bounds.size.height - 64) collectionViewLayout:flowLayout]; //2.為collection 註冊cell(自定義的cell) [collectionView registerNib:[UINib nibWithNibName:@"CarCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CarCollectionViewCell"];
還要為它設置代理和實現代理方法:
collectionView.backgroundColor = [UIColor whiteColor]; self.collectionView = collectionView; self.collectionView.delegate = self; self.collectionView.dataSource = self; [self.view addSubview:self.collectionView];
設置cell的大小:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { CGSize size = CGSizeMake(80, 100); return size; }
設置整體cell在collection中的上下左右邊距:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ return UIEdgeInsetsMake(30, 20, 0, 20); }
在cellForItemAtIndexPath中使用自定義的cell,註意自定義cell的xib文件時,要加上identifier:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ CarCollectionViewCell *cell = (CarCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CarCollectionViewCell" forIndexPath:indexPath]; ... ... ...
return cell; }