如何自定義CollectionView中每個元素的大小和間距


問題: 讓每個元素大小變為104 x 104

Step 1:

在你的視圖控制器頭文件中實現UICollectionViewFlowLayout協議

eg:

@interface XXViewController : UICollectionViewController<UICollectionViewFlowLayout>

...

@end

 

Step 2:

設置每個單元格的大小

eg:

- (CGSize) collectionView:(UICollectionView *)collectionView
  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
  return CGSizeMake(104.0f, 104.0f);
}

 

Step 3:

設置單元格間的橫向間距

eg:

- (CGFloat) collectionView:(UICollectionView *)collectionView
    layout:(UICollectionViewLayout *)collectionViewLayout
    minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2.0f;
}

 

Step 4:

設置縱向的行間距

eg:

- (CGFloat) collectionView:(UICollectionView *)collectionView
    layout:(UICollectionViewLayout *)collectionViewLayout
    minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 2.0f;
}

 

step 5:

通過調整inset使單元格頂部和底部都有間距(inset次序: 上,左,下,右邊)

eg:

- (UIEdgeInsets) collectionView:(UICollectionView *)collectionView
    layout:(UICollectionViewLayout *)collectionViewLayout
    insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(2.0f, 0.0f, 2.0f, 0.0f);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM