推广

iOS UICollectionView的动态布局及内容自适应大小

iseeyu3年前 (2023-11-16)推广204

image.png

,而且如果这些标签需要动态设置将变得更加复杂。
本文通过UICollectionView来实现这些需求。由于展示内容通过服务端动态控制,所以这里首先要做的就是让collectionView的cell大小能够自适应文字的宽度。然后才是动态设置collectionView的尺寸。

计算cell的大小

由于计算文字宽度的代码都是通用的,直接在sizeForItemAtIndexPath方法中返回cell的宽度和高度。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *attribute = @{NSFontAttributeName: self.textFont};
    CGSize currentLabelSize = [self.dataAry[indexPath.item] sizeWithAttributes:attribute];
    
    return CGSizeMake(ceil(currentLabelSize.width) + self.leftAndRightSpacing*2, self.itemCellHeight);
}

但是设置完以后可能会发现item的间距并不是固定的,如下图:

image.png

重写UICollectionViewFlowLayout方法

要让collectionView整齐排布,就要用到flowLayout,这里通过继承UICollectionViewFlowLayout来重新对collectionView进行布局。UICollectionViewFlowLayout是一个布局类继承自UICollectionViewLayout,主要涉及以下两个方法:

- (CGSize)collectionViewContentSize; 

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;

collectionViewContentSize这个方法,用来返回collectionView的内容的大小,并不是UICollectionView的frame大小。
layoutAttributesForElementsInRect,这里就是返回所有布局属性的数组。
通过重写这两个方法,就可以重新对content进行布局了,这样每个cell的排列就可以紧凑起来了。

首先自定义个类继承自UICollectionViewFlowLayout,定义所需要的属性

@interface LiveBroadcastFlowLayout : UICollectionViewFlowLayout

///数组内容
@property (nonatomic, strong) NSArray *dataArry;
///item高度
@property (nonatomic, assign) CGFloat itemHeight;
///item左右偏移
@property (nonatomic, assign) CGFloat itemWidthSpacing;
///展示字体
@property (nonatomic, strong) UIFont *textFont;
///UICollectionView宽度
@property (nonatomic, assign) CGFloat contentWidth;

@end

通过代码注释,可以了解重写的方法及作用。
计算ContentSize的大小:

- (CGSize)collectionViewContentSize{
    CGSize size = CGSizeZero;
    NSInteger itemCount = 0;
//获取collectionView的item个数,为0的话返回CGSizeZero
    if ([self.collectionView.dataSource respondsToSelector:@selector(collectionView:numberOfItemsInSection:)]) {
        itemCount = [self.collectionView.dataSource collectionView:self.collectionView numberOfItemsInSection:0];
    }
    if (CGSizeEqualToSize(size, CGSizeZero) && itemCount == 0) {
        return CGSizeZero;
    }
//内容宽度
    NSInteger lineWidth = 0;
//展示行数
    NSUInteger rowCount = 1;
    for (int i = 0; i < itemCount; ++i) {
//self.dataArry为内容数组
//根据传入的字体大小self.textFont计算item宽度
//然后与传入的collectionView的宽度self.contentWidth做计算
        NSDictionary *attribute = @{NSFontAttributeName: self.textFont};
        CGSize currentLabelSize = [self.dataArry[i] sizeWithAttributes:attribute];
//self.itemWidthSpacing为展示预留的宽度,根据需求设置
        CGFloat cellWidth = currentLabelSize.width + self.itemWidthSpacing*2;
        if (i == (itemCount - 1)) {
            lineWidth = lineWidth + cellWidth;
        } else {
            lineWidth = lineWidth + self.minimumInteritemSpacing + cellWidth;
        }
//计算一行的item展示数量
        if (lineWidth > (NSInteger)self.contentWidth) {
            rowCount++;
            lineWidth = cellWidth + self.minimumInteritemSpacing + cellWidth;
        }
    }
//最终计算出collectionView内容展示所需的高度
    size.width = self.contentWidth;
    size.height = rowCount * self.itemHeight + (rowCount - 1) * self.minimumLineSpacing  + self.sectionInset.top + self.sectionInset.bottom;
    
    return size;
}

控制collectionView内部item布局的展示:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
//将第一个item固定在左上,防止一行只展示一个item时位置错乱
    if (attributes.count > 0) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[0];
        CGRect frame = currentLayoutAttributes.frame;
        frame.origin.x = 0;
        currentLayoutAttributes.frame = frame;
    }
    
    for(int i = 1; i < [attributes count]; ++i) {
        NSDictionary *attribute = @{NSFontAttributeName: self.textFont};
        CGSize labelSize = [self.dataArry[i] sizeWithAttributes:attribute];
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        CGFloat cellWidth = ceil(labelSize.width) + self.itemWidthSpacing*2;
        currentLayoutAttributes.size = CGSizeMake(cellWidth, self.itemHeight);
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
//如果当前item的宽度+前一个item的最大宽度+item间距<=collectionView的宽度,则一行可以容纳下,修改当前item的x轴位置,否则居左显示
        if (origin + self.minimumInteritemSpacing + currentLayoutAttributes.frame.size.width < self.contentWidth) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + self.minimumInteritemSpacing;
            currentLayoutAttributes.frame = frame;
        } else {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = 0;
            currentLayoutAttributes.frame = frame;
        }
    }

    return attributes;
}

layoutAttributesForElementsInRect方法中,这里从第二个item开始,每个cell的位置都是前一个cell的位置+maximumSpacing,如果不超过这一行的最大宽度,就改变当前cell的起始位置和大小(也即frame)。如果超过了就不改变,那不改变是什么意思?就是保持原来的位置,这里的原来的位置可能和我们想象的不太一样,不是一开始定死的位置,而是经过调整后的位置,因为,这里改变前一个cell对后面的cell是好有影响的,应该是后面的y轴位置会自动调整。

还没结束

很多时候UICollectionView并不是单独使用,更多的是嵌套在UITableView的cell中,负责一小部分内容的展示。

那么如何在UITableViewCell中动态调整UICollectionView的大小高度呢?

首先

在UITableViewCell添加UICollectionView并设置约束:

image.png

除了坐标位置外,重点设置UICollectionView的宽,高约束,这边随便设置个值(接近真实大小就行)。

然后

把宽,高的约束通过xib关联起来

@interface MyLiveBroadcastCollectView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (weak, nonatomic) IBOutlet LiveBroadcastFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pictureCollectionViewHeightCons;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pictureCollectionViewWidthCons;

@property (nonatomic, strong) NSArray *dataAry;

@end

通过外部调用方法em_displayWithID:

- (void)em_displayWithID:(id)model{
    self.dataAry = model;
    self.flowLayout.dataArry = model;
    [self reloadData];
    
    //[tableview reload]的时候是异步操作,[UICollectionView reloadData]实际上并没有加载完所有的item
    //所以collectionViewLayout.collectionViewContentSize不准
    //所以就需要重写collectionViewLayout
    CGFloat updateHeight = self.collectionViewLayout.collectionViewContentSize.height;//这里就拿最新撑开的ContentSize去更新高度约束。
    
    self.pictureCollectionViewHeightCons.constant = updateHeight;
    self.pictureCollectionViewWidthCons.constant = self.contentWidth;
}

这边返回的updateHeight是通过重写方法后计算得出的,而self.contentWidth则通过[UIScreen mainScreen].bounds.size.width计算来固定,因为UITableViewCell通过layoutIfNeeded后才能得出UICollectionView的真实宽度,所以暂时只适用于UICollectionView宽度固定的情况。

接下来

通过对UITableViewCell的赋值来完成方法的调用

- (CGFloat)calculateRowHeightWithId:(id)model{
    self.dataModel = model;
    
    if (self.dataModel.height != 0) {
        return self.dataModel.height;
    }
    
    [self em_displayWithID:self.dataModel];
    
    [self layoutIfNeeded];
    
    self.dataModel.height = CGRectGetMaxY(self.stackView.frame);
    return CGRectGetMaxY(self.stackView.frame);
}

- (void)em_displayWithID:(id)model{
    self.dataModel = model;
    /*.省略方法.*/
    [self.tagsCollectionView em_displayWithID:self.dataModel.tagArry];
}

通过调用UITableViewCell的计算高度方法calculateRowHeightWithId,在UITableViewCell的em_displayWithID:方法中对UICollectionView进行赋值方法的调用。

最后,附上效果图的样子:

image.png

参考文章和源码:
AutoLayout下CollectionView的自适应大小

扫描二维码推送至手机访问。

版权声明:本文由西安泽虎代运营发布,如需转载请注明出处。

转载请注明出处https://www.0291.com.cn/post/56639.html

相关文章

西安企业做百度推广,一个月花三千和花三万到底差在哪?

4|最近跟几个西安的老板聊天,发现一个挺有意思的现象:同样做百度推广,有人一个月花三千块,询盘不断;有人一个月砸三万,水花都没见着。问他们区别在哪,大多数人说不清楚,只知道'钱花了,没效果'。 5| 6|百度推广这东西,说复杂也复杂,说简单也简单。核心就一件事:让你的潜在客户搜某个词的时候,你的信息...

我想当策划,大学应该选什么专业?

我想当策划,大学应该选什么专业?

学,广告,传播,公关,这些专业其实都可以。另外也可以学像汉语言文学,以及一些跟文学相关的一些专业,会对你找工作有帮助。但是,你想从事这个这份职业,除了专业的学习之外,更多的是,你要在上学的时候积极参与一些更营销策划相关的社会实践。比如说你可以做一些兼职,比如说帮别人去写稿,...

服装市场营销策略分析,“定位不慎满盘皆输”

服装市场营销策略分析,“定位不慎满盘皆输”

不同的区域需要不同的策略,而不同的营销策略需要不同的销售思路来配合。因此,在研究女装产品销售思路之前,最好先对于市场与营销策略做一次深入地了解。1.市场区域化(market segmentation):目标营销的第一步,是将整个市场拆分成若干个同性质的小市场。2.目标市场的...

晚间悦读丨你的思维方式,决定你的人生高度!

晚间悦读丨你的思维方式,决定你的人生高度!

越长大,越发现,能够决定你人生高度的,往往是你的认知层次。 你的认知在哪个层级,你的人生就处在什么状态。你认知的高度,决定了你人生的高度。 那如何才能升级方式、提升认知能力呢?可以从这三个方面做出改变。 NO. 1 改变态度 有人...

编写项目营销策划方案六大要点

编写项目营销策划方案六大要点

现在商业发展非常迅速,的需求非常的大,但是要做好营销策划是有一定难度的,我把自己做营销策划的一些体会在这里分享给朋友们。营销策划方案六大要点我们先说项目营销策划方案这个话题。大部分的营销策划人都是在企业里工作,大部分项目之初都是来源于一个想法,创始人、老板或者创始团队的一个...

【商场营销策划】如何进行商场营销策划?

【商场营销策划】如何进行商场营销策划?

商场是策划者们关注的永恒话题,那么究竟该如何作好商场营销策划呢?掌握以下这几点营销策略设计原则,至关重要!1.义利兼顾的原则。商场在获取利润的同时要充分考虑到消费者的合法利益和商场的长远利益。在作商场活动营销策略方案的时候应该将这一点作为首要的原则。对商场有利而对顾客不利的...

现在,非常期待与您的又一次邂逅

我们努力让每一部企业宣传片和抖音短视频成为商业大片