zoukankan      html  css  js  c++  java
  • OC CollectionView和TableView自身高度的隐式递归计算,改变父试图布局

    CollectionView和TableView自身高度的隐式递归计算

    1、前沿:我们一般会碰到这样的需求,一个tableview或者一个colletionview放在一个scrollview上边,而tableview和collectionview的cell是不可控的,更具请求内容变化而变化。如图:(标签的多少和标签的长度不一样,然而下边又有一个可以跟着滑动的view)

    思路一:根据请求的内容一个一个计算宽度,然后计算行数,根据:表头+线宽(为了准确)+行间距*行间距个数+行高度*行数+区头+区尾

    我也这样考虑过,但是这样计算量不言而喻。

    思路二:考虑最后一个cell的右下定点坐标加上一定的高度转化为tableview的高度,然后走了一点弯路:

    cellForItemAtIndexPath//方法

    使用隐式递归:(为什么叫隐式递归说明:因为不是写的递归算法,而是使用cell的重用算法)

    - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        XYimprovenCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        CGPoint point =  [cell convertPoint:CGPointMake(cell.width, cell.height) toView:self];
        self.height = fabs(point.y) + 20;
        return cell;
    }

    让每一次cell的右边定点定于collection的高度;

    问题:重用的时候是先加载cell然后赋值高度,不出现的时候将不加载。

    然后使用:

    - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
        CGPoint point =  [cell convertPoint:CGPointMake(cell.width, cell.height) toView:self];
        self.height = fabs(point.y) + 20;
        if (indexPath.row == _titleArry.count - 1) {//限制在最后一个cell加载时候才返回高度
            if (self.allHeight) {
                self.allHeight(self.height);
            }
        }
        
    }

    因为是cell的reload方法加载cell,在外边使用这个高度更新别的frame:

    _improvenCollectionView.allHeight = ^(CGFloat height) {
                STRONGSELF
               //更新高度
                strongSelf.bgScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, strongSelf.improvenCollectionView.maxY +  123);
                strongSelf.buttonSure.frame = CGRectMake(21, 20 + strongSelf.improvenCollectionView.maxY,SCREEN_WIDTH - 2 *21,40);
            };

    是不是有种多么痛的领悟,转载请标明出处!

  • 相关阅读:
    一线架构师实践指南读后感
    可修改性战术
    软件架构师如何工作?
    寒假学习第十五天
    寒假学习第十四天
    寒假学习第十三天
    寒假学习第十二天
    寒假学习第十一天
    寒假学习第十天
    如何变得聪明
  • 原文地址:https://www.cnblogs.com/PeterWolf/p/11170110.html
Copyright © 2011-2022 走看看