ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

iOS sizeForItemAtIndexPath方法在iOS14下变化

2021-07-21 16:04:11  阅读:174  来源: 互联网

标签:indexPath CGSizeMake iOS14 collectionView iOS width model sizeForItemAtIndexPath


对于UICollectionViewDelegateFlowLayout的sizeForItemAtIndexPath这个方法大家都很熟悉,这个代理方法就是返回每个item尺寸的方法

@protocol UICollectionViewDelegateFlowLayout <UICollectionViewDelegate>
@optional

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

在这个方法中有时我们需要动态计算每个item的size,此时我们就需要从数组中取出数据源,然后计算。

那么问题来了,是否需要判断数组越界的问题?

经实测iOS14之前,可以直接取值计算,不需要担心数组越界的问题。

A:代码如下

#pragma mark -- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TaskValueModel *model = self.model.orgRelationCollection[indexPath.row];
    NSString *str = ObjErrorCheck(model.value);
    
    CGRect itemFrame = [str boundingRectWithSize:CGSizeMake(LL_ScreenWidth -74, 14) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
    
    CGFloat width = itemFrame.size.width + 24;
    return CGSizeMake(width, 32);
}

但是iOS14之后就必须处理数组越界的问题,否则直接crash

B:代码如下

#pragma mark -- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.model.orgRelationCollection.count) {
        TaskValueModel *model = self.model.orgRelationCollection[indexPath.row];
        NSString *str = ObjErrorCheck(model.value);
        
        CGRect itemFrame = [str boundingRectWithSize:CGSizeMake(LL_ScreenWidth -74, 14) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
        
        CGFloat width = itemFrame.size.width + 24;
        return CGSizeMake(width, 32);
    } else {
        return CGSizeZero;
    }
}

综上所述:

我们应该采取B方案处理

备注:

不论是这个涉及系统适配的问题,还是别的什么问题,涉及数组的,从严谨的角度考虑,我们都应该做越界的容错处理

标签:indexPath,CGSizeMake,iOS14,collectionView,iOS,width,model,sizeForItemAtIndexPath
来源: https://www.cnblogs.com/lijianyi/p/15039881.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有