UIScrollView 的非凡之处就在于当它遇到了 AutoLayout 之后其 contentSize 的计算规定有些非凡。
contentSize 是依据子视图的 leading/trailing/top/bottom 进行确定的
所以防止咱们手动去设置 contentSize
,咱们必须投合它的规定去设置
间接上代码
let scrollView = UIScrollView()
scrollView.backgroundColor = .gray
view.addSubview(scrollView)
scrollView.snp.makeConstraints {(make) in
make.edges.equalToSuperview()}
let containerView = UIView()
containerView.backgroundColor = .blue
scrollView.addSubview(containerView)
containerView.snp.makeConstraints {(make) in
make.edges.equalToSuperview()
make.width.equalToSuperview()}
let view1 = UIView()
view1.backgroundColor = .orange
let view2 = UIView()
view2.backgroundColor = .blue
containerView.addSubview(view1)
containerView.addSubview(view2)
view1.snp.makeConstraints {(make) in
make.top.equalToSuperview()
make.width.equalToSuperview()
make.height.equalTo(500)
}
view2.snp.makeConstraints {(make) in
make.top.equalTo(view1.snp.bottom)
make.bottom.equalTo(containerView.snp.bottom)
make.leading.trailing.equalTo(containerView)
make.width.equalToSuperview()
make.height.equalTo(500)
}
大略就是这意思,咱们通过一个填满的 containerView
去设置子视图,同时咱们最初一个 subview
的 bottom
肯定要与 containerView
对齐即可