使用snapkit完成自适应高度的scrollview

有2点要注意的:

  • 所有view都记得设置width,如果子view还要设置height
  • 最后一个view记得设置bottom与contentView的底部对齐

代码如下:

let scrollView = UIScrollView()
        let contentView = UIView()
        contentView.backgroundColor = UIColor.greenColor()
        let view1 = UIView()
        view1.backgroundColor = UIColor.redColor()
        let view2 = UIView()
        view2.backgroundColor = UIColor.blueColor()
        
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        contentView.addSubview(view1)
        contentView.addSubview(view2)
        
        scrollView.snp_makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        contentView.snp_makeConstraints { (make) in
            make.edges.equalTo(scrollView)
            make.width.equalTo(view)
        }
        
        view1.snp_makeConstraints { (make) in
            make.top.equalTo(contentView)
            make.leading.trailing.equalTo(contentView)
            make.width.equalTo(contentView)
            make.height.equalTo(500)
        }
        
        view2.snp_makeConstraints { (make) in
            make.top.equalTo(view1.snp_bottom)
            make.bottom.equalTo(contentView.snp_bottom)
            make.leading.trailing.equalTo(contentView)
            make.width.equalTo(contentView)
            make.height.equalTo(500)
        }

 

Leave a Reply

Your email address will not be published.