要點:
UIScrollView是依靠與其子視圖(subview)之間的約束來確定ContentSize的大小
缘挽,如果不設(shè)置好子view的寬高度約束的話掖肋,就會造成UISCrollView顯示異常油啤。
對于UIScrollView的subview來說撒蟀,它的leading/trailing/top/bottom的space是相對于UIScrollView的contentSize而不是bounds來確定的虽风,換句話說:UIScrollView與其subview之間相對位置的約束并不會直接用于frame的計算,而是會轉(zhuǎn)化為對ContentSize的計算咆瘟。(摘自
:https://blog.csdn.net/longshihua/java/article/details/78441466)
錯誤用法
沒有指定greenView的 寬高嚼隘, 無法顯示scrollView
let scrollView = UIScrollView()
scrollView.delegate = self
scrollView.backgroundColor = .blue
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
let greenView = UIView()
greenView.backgroundColor = .green
scrollView.addSubview(greenView)
greenView.snp.makeConstraints { (make) in
make.leading.trailing.equalToSuperview()
make.top.equalToSuperview()
make.bottom.equalToSuperview()
}
2、對subviews指定寬高袒餐,讓最底部的view設(shè)置對scrollView的約束飞蛹,可顯示,但是會有布局異常灸眼。
let scrollView = UIScrollView()
scrollView.delegate = self
scrollView.backgroundColor = .blue
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
let greenView = UIView()
greenView.backgroundColor = .green
scrollView.addSubview(greenView)
greenView.snp.makeConstraints { (make) in
make.top.leading.equalToSuperview()
make.width.equalTo(300)
make.height.equalTo(100)
}
let redView = UIView()
redView.backgroundColor = .red
scrollView.addSubview(redView)
redView.snp.makeConstraints { (make) in
make.leading.equalToSuperview()
make.top.equalTo(greenView.snp.bottom)
make.width.equalTo(300)
make.height.equalTo(1000)
make.bottom.equalToSuperview() // 不添加底部的約束 則無法滾動
}
正確用法
對scrollView 添加contentView卧檐,讓subviews添加對contentView的約束,而contentView只需處理contentSize的寬度
let scrollView = UIScrollView()
scrollView.delegate = self
scrollView.backgroundColor = .blue
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
contentView = UIView()
contentView.backgroundColor = .yellow
scrollView.addSubview(contentView)
contentView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.width.equalTo(300)
// 設(shè)置contentSize的 width值
}
let redView = UIView()
redView.backgroundColor = .red
contentView.addSubview(redView)
redView.snp.makeConstraints { (make) in
make.leading.top.trailing.equalToSuperview()
make.height.equalTo(400)
}
let greenView = UIView()
greenView.backgroundColor = .green
contentView.addSubview(greenView)
greenView.snp.makeConstraints { (make) in
make.leading.trailing.equalToSuperview()
make.height.equalTo(600)
make.top.equalTo(redView.snp.bottom)
make.bottom.equalToSuperview()
// 固定底部約束焰宣,設(shè)置好contentSize的 height值
}