//設置cell的尺寸 - (instancetype)init{ UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; CGFloat listScreenW = screenW; int cols = listCollectionCellCount; CGFloat inset = listScreenW/(cols + 0.2069); layout.itemSize = CGSizeMake(inset, inset); return [self initWithCollectionViewLayout:layout]; } //在屏幕尺寸發生改變狀況下調用該方法(在這了能夠設置cell之間的間距) - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{ int cols = listCollectionCellCount; UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout; CGFloat inset = (size.width - cols*layout.itemSize.width)/(cols + 1); layout.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset); layout.minimumLineSpacing = inset; } - (void)viewDidLoad{ //從XIB中加在cell [self.collectionView registerNib:[UINib nibWithNibName:@"listCollectionViewController" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier]; } //下面的方法較複雜 UINib *nib = [UINib nibWithNibName:@"DZListCollectionViewCell" bundle:[NSBundle mainBundle]]; [collectionView registerNib:nib forCellWithReuseIdentifier:reuseIdentifier]; DZListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = @"MyCell"; static BOOL nibMyCellloaded = NO; if(!nibMyCellloaded) { UINib *nib = [UINib nibWithNibName:@"MyCell" bundle: nil]; [cv registerNib:nib forCellWithReuseIdentifier:identifier]; nibMyCellloaded = YES; } MyCell *cell = (MyCell*)[cv dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath]; cell.labelCell.text = @"Text"; return cell; }