3

给我两分钟的时间:微博风格九宫格:UICollectionView实现 - GarveyCalvin

 1 year ago
source link: https://www.cnblogs.com/GarveyCalvin/p/17124808.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

给我两分钟的时间:微博风格九宫格:UICollectionView实现

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 有超出屏幕而导致换行的问题

684349-20230215212950762-1460369806.png

在这篇文章中,我们学习了如何用 UICollectionView 来制作九宫格布局。希望这篇文章能为大家带来帮助,快来关注我,让我们一起努力!

博文作者:GarveyCalvin

公众号:凡人程序猿

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

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

本文版权归作者所有,欢迎转载,但必须保留此段声明,并给出原文链接,谢谢合作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK