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
對齊即可