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
对齐即可