Swift UITableView自动计算cell高度、缓存、动态更改布局

需求页面大概是这个样子

需求页面

底部显示的是图片,是动态变化的,文本内容也是动态改变的

实现过程

首先用到了这个代理方法 让cell自适应

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        let height = self.heightDic[indexPath] as? NSNumber
        if height != nil {
            return CGFloat(height!.floatValue)
        }else {
            return 100
        }
    }

不设置固定高度

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

缓存高度

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let height = NSNumber(value: Float(cell.frame.size.height))
        self.heightDic[indexPath] = height  
    }

动态改变的viewframe 需要重新布局 updateConstraints


  func configWithModel(_ model: CYListModel, indexRow: Int) {
        contentLab.text = model.content
        self.showView.removeFromSuperview()
        reloadShowView()
          if indexRow % 2 == 0 {
            self.showView.snp.updateConstraints {
                $0.height.equalTo(100)
            }
        }else {
            self.showView.snp.updateConstraints {
                $0.height.equalTo(10)
            }
        }

    }
    

示例:demo

如果出现类似这种 警告

Will attempt to recover by breaking constraint 
<SnapKit.LayoutConstraint:0x60c0004a5340@GSDynamicCell.swift#265 UIView:0x7fa5f5eddad0.height == 363.0>

可以尝试给一个priority(100)

      imageBgView.snp.makeConstraints {
            $0.top.equalTo((weakSelf?.contentLab.snp.bottom)!).offset(16).priority(100)
            $0.left.equalTo((weakSelf?.contentLab)!)
            $0.height.equalTo(100)
            $0.right.equalTo((weakSelf?.contentLab)!)
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,019评论 3 119
  • 【8】大排场 还在睡梦中,突然被外面的轰鸣声震醒!我骂了句讨厌,睡眼惺忪拉开窗帘一看,顿时傻了。只见...
    一点文字阅读 2,052评论 45 88
  • 英语零基础,怎么样才能读完一本英文书呢? 我有一个好消息和一个坏消息—— 好消息是,零基础读英文原版书…是不可能的...
    张廷慧阅读 2,066评论 0 10
  • 写一篇博客需要消费的精力是很多的,通常自己一个人写程序的时候完全不需要考虑需要怎么给别人讲我写的思路,顶多就是加上...
    老梁家的风子阅读 639评论 6 1
  • fuwa是一个进行snv/indel检测的工具,采用的是决策树(CART)算法。这里仅仅观察文中用来作为分类的特征...
    井底蛙蛙呱呱呱阅读 1,830评论 0 0