做九宮格布局時,可以用 UIScrollView,也可以用 UICollectionViewController。相較之下,後者更方便,能省去不少麻煩,例如橫豎屏的自適應。只需簡單幾步,就能做出漂亮的九宮格布局。
建立 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;
UICollectionViewController *controller = [[UICollectionViewController alloc] initWithCollectionViewLayout:layout];
在對 UICollectionViewController 的 View 做屬性設定時,記得要透過 controller.collectionView 來設置:
self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_deal"]];
別忘了實作 <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 的組合,再搭配流式布局的自動換行,就能輕鬆完成橫屏與豎屏皆自適應的九宮格效果。