iOS-tableHeaderView利用自动布局自适应高度

效果:

关键点0:

headerView的子View的布局一定要从headerView的最上面开始填充,然后依次往下面设置布局

private func setupSubViews(){
        topView = UIView()
        topView.backgroundColor = YZJRandomColor()
        addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(self)
            make.height.equalTo(99)
        }
        
        middleView = UIView()
        middleView.backgroundColor = YZJRandomColor()
        addSubview(middleView)
        middleView.snp.makeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(103)
        }
        
        bottomView = UIView()
        bottomView.backgroundColor = YZJRandomColor()
        addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.top.equalTo(middleView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(129)
        }
}

关键点1:

第一次显示的时候,需要在headerView类的didMoveToSuperview里面设置布局(宽度的布局一定要设置)

override func didMoveToSuperview() {
        super.didMoveToSuperview()
        if superview != nil{
            snp.remakeConstraints { (make) in
                make.width.equalTo(superview!)
                make.bottom.equalTo(bottomView)
            }
            layoutIfNeeded()
        }
}

关键点2:

headerView布局修改后需要调用superview?.layoutIfNeeded(),并重新赋值tableViewtableHeaderView

        topView.snp.remakeConstraints { (make) in
            make.left.right.top.equalTo(self)
            make.height.equalTo(randomHeight())
        }
        middleView.snp.remakeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(randomHeight())
        }
        
        bottomView.snp.remakeConstraints { (make) in
            make.top.equalTo(middleView.snp.bottom)
            make.left.right.equalTo(self)
            make.height.equalTo(randomHeight())
        }
        superview?.layoutIfNeeded()
        headerView.change()
        tableView.tableHeaderView = headerView

关键点3(iOS9会有影响):

  • 使用自动布局的时候先设置tableView的布局再给tableView.tableHeaderView赋值
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        tableView.tableHeaderView = headView
  • headerView里面只能有一个外包的容器View,不能容器View再套容器View进行自适应(外部的容器View布局依赖于里面容器View的布局)

demo地址

你可能感兴趣的:(iOS-tableHeaderView利用自动布局自适应高度)