

我們在做九宮格布局時,可以使用UIScrollView,也可以使用UICollectionViewController。
當我們用UICollectionViewController來進行九宮格布局,可以更加方便,省去很多麻煩,例如橫豎屏的適配。
UICollectionViewController 用起來非常簡單,只需要簡單的幾步,就能實現非常的漂亮的九宮格布局。
下面就說說UICollectionViewController實現的幾步。
首頁創建UICollectionViewController時,需要給它傳一個展示的布局,一般九宮格用的都使流水布局!
// 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;
//初始化 UICollectionViewControllerUICollectionViewController *controller = [[UICollectionViewController alloc] initWithCollectionViewLayout:layout]
在對 UICollectionViewController 的 View 進行相關屬性設置和屬性修改時,記得要拿到UICollectionViewController.collectionView 再設置。
//設置背景self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_deal"]];
記得分別實現
<UICollectionViewDelegate, UICollectionViewDataSource>
之后再調用代理數據源方法和代理方法
#PRagma mark - 數據源方法 2 /** 3 * 第section組有多少個格子(cell) 4 */ 5 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 6 { 7 return _deals.count; 8 } 9 10 //每個格子的內容11 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath12 {13 // indexPath.item 某一組的哪一個14 // indexPath.section 哪一組15 // 1.創建cell16 QCDealCell *cell = [QCDealCell cellWithCollectionView:collectionView indexPath:indexPath];17 18 // 2.取出模型,傳遞模型19 cell.deal = _deals[indexPath.item];20 21 return cell;22 }
模型數據封裝好后,就能實現上圖展示效果,橫豎屏自動適配好!
清澈Saup
新聞熱點
疑難解答