Stories

Detail Return Return

給我兩分鐘的時間:微博風格九宮格:UICollectionView實現 - Stories Detail

引言

UICollectionView 是 iOS 平台上一種強大的視圖佈局工具,能夠很好地實現網格佈局,列表佈局等多種佈局方式。

首先講下今天的目標,我們將要使用 UICollectionView 來創建仿微博的九宮格內容。首先,目標行數為3,每行顯示3張圖片,總共顯示9張圖片。

實現方式

我們往界面上添加一個 UICollectionView,並創建一個 UICollectionViewFlowLayout 佈局類,這裏的實現為懶加載的方式:

- (UICollectionView *)collectionView {
    if (!_collectionView) {
	    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.scrollEnabled = NO; // 設置不讓滑動
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

為自定義 cell 註冊到 UICollectionView 中:

[_collectionView registerClass:[GCImageGridCell class] forCellWithReuseIdentifier:kGCImageGridCell];

然後,我們設置 UICollectionView 的數據源協議:

_collectionView.dataSource = self;

接着實現 UICollectionView 的協議內容:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.datas.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GCImageGridCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kGCImageGridCell forIndexPath:indexPath];
    NSString *imgName = self.datas[indexPath.row];
    cell.imgView.image = [UIImage imageNamed:imgName];
    return cell;
}

接着,設置前面的 UICollectionViewFlowLayout 的屬性,將滑動的方向設置為縱向滑動:

layout.scrollDirection = UICollectionViewScrollDirectionVertical; //設置佈局方式為縱向佈局

接下來,計算每個 item 的大小、item 之間的間距和行距、每個分組之間的間距:

CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
CGFloat horizontal = 16; // 左右邊距
CGFloat itemSpace = 6; // item 的間距
CGFloat itemSize = (screenWidth - horizontal * 2 - itemSpace * 2) / 3; // 計算每個 item 的大小
layout.minimumLineSpacing = itemSpace;
layout.minimumInteritemSpacing = itemSpace;
layout.sectionInset = UIEdgeInsetsMake(0, horizontal, 0, horizontal);
layout.itemSize = CGSizeMake(floor(itemSize), floor(itemSize));

注意:計算item大小時使用到了floor函數向下取整,這是防止每行的 item 有超出屏幕而導致換行的問題

效果呈現

總結

在這篇文章中,我們學習瞭如何用 UICollectionView 來製作九宮格佈局。希望這篇文章能為大家帶來幫助,快來關注我,讓我們一起努力!

關於作者

博文作者:GarveyCalvin

公眾號:凡人程序猿

微博:https://weibo.com/feiyueharia

博客園:https://www.cnblogs.com/GarveyCalvin

本文版權歸作者所有,歡迎轉載,但必須保留此段聲明,並給出原文鏈接,謝謝合作!

user avatar sishuiliunian_58f891c129ab1 Avatar segfal_coder Avatar jingdongkeji Avatar gddg Avatar 2022-yang Avatar
Favorites 5 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.