您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS:用 UICollectionViewController 實現橫豎屏九宮格布局

編輯:iOS 開發綜合

1. 為何選擇 UICollectionViewController

做九宮格布局時,可以用 UIScrollView,也可以用 UICollectionViewController。相較之下,後者更方便,能省去不少麻煩,例如橫豎屏的自適應。只需簡單幾步,就能做出漂亮的九宮格布局。

2. UICollectionViewController 的實作

2.1 傳遞布局

建立 UICollectionViewController 時,需傳入一個布局物件,九宮格通常用流水布局(UICollectionViewFlowLayout):

// 1. 創建流水布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
// 2. 設置每個格子的尺寸
layout.itemSize = CGSizeMake(250, 250);
// 3. 設置整個 collectionView 的內邊距
CGFloat paddingY = 20;
CGFloat paddingX = 40;
layout.sectionInset = UIEdgeInsetsMake(paddingY, paddingX, paddingY, paddingX);
// 4. 設置每一行之間的間距
layout.minimumLineSpacing = paddingY;

2.2 初始化並設定布局

UICollectionViewController *controller = [[UICollectionViewController alloc] initWithCollectionViewLayout:layout];

在對 UICollectionViewController 的 View 做屬性設定時,記得要透過 controller.collectionView 來設置:

self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_deal"]];

2.3 顯示數據

別忘了實作 <UICollectionViewDelegate, UICollectionViewDataSource> 協議,再實作資料源與代理方法:

#pragma mark - 數據源方法
// 該 section 有多少個格子(cell)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _deals.count;
}

// 每個格子的內容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // indexPath.item 表示某一組的哪一個,indexPath.section 表示哪一組
    QCDealCell *cell = [QCDealCell cellWithCollectionView:collectionView indexPath:indexPath];
    cell.deal = _deals[indexPath.item];
    return cell;
}

透過 itemSize、sectionInset 與 minimumLineSpacing 的組合,再搭配流式布局的自動換行,就能輕鬆完成橫屏與豎屏皆自適應的九宮格效果。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved