UIScrollView 遇到了AutoLayout之后其contentSize 的计算
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
对齐即可