zoukankan      html  css  js  c++  java
  • iOS sizeForItemAtIndexPath方法在iOS14下变化

    对于UICollectionViewDelegateFlowLayoutsizeForItemAtIndexPath这个方法大家都很熟悉,这个代理方法就是返回每个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方案处理

    备注:

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

  • 相关阅读:
    计算机二级-C语言-程序修改题-190114记录-对整型变量进行取余操作可以取得各个位上的值。
    计算机二级C语言选择题错题知识点记录。
    计算机二级-C语言-对文件的读写操作。链表的定义与赋值。对字符串的遍历和处理。
    二十七、Java基础之数组的排列
    二十六、Java语言之二维数组
    二十五、Java基础之一维数组
    二十四、Java基础之自定义异常
    二十三、Java基础之异常及异常处理机制
    二十二、Java基础之内部类
    二十一、Java基础之访问控制权限
  • 原文地址:https://www.cnblogs.com/lijianyi/p/15039881.html
Copyright © 2011-2022 走看看