所以我有一个scrollView
,在scrollView
里面是一个stackView
,它包含了屏幕上所有的views
。
问题是我的stackView
有许多可隐藏的views
,所以我需要调整我的containsVieww's height
基于我的stackView's height
我的psuedo代码应该像这样:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(stackView.bounds.height)
// do logic to change contentView size here
}
func setupView(){
scrollView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
scrollView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
scrollView.backgroundColor = .white
scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height)
scrollView.addSubview(stackView)
stackView.setArrangedSubView(views: [label1, label 2, label 3, label 4, ..., label n]
[label1, label 2, label 3].isHidden = true
}
func onHitButton(){
if isHidden {
[label1, label 2, label 3].isHidden = false
isHidden = false
} else {
[label1, label 2, label 3].isHidden = true
isHidden = true
}
print(stackView.bounds.height) // still return the ex height
}
问题是:
第一个init
,我的[label1,2,3].isHidden = true
,我的stackViewHeight
是500
当我的onHitButton
被调用时,我的[label1,2,3].isHidden = false
,我的stackViewHeight
仍然是500
,但屏幕显示正确,那些labels
现在可见,我的stackView
被拉伸。当然,我的scrollView
不能正确显示。
然后我再次点击我的onHitButton
,那些labels
被隐藏,我的stackView
在屏幕上收缩,但stackViewHeight
返回850
?
应该是相反的。
我还试图在另一个button
调用上print
height
,它返回正确的height
?看来viewDidLayoutSubviews
打电话太早了。
总而言之:stackView
返回高度,然后再调整self
使用自动布局将堆栈视图约束为滚动视图的内容布局指南:
scrollView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
// reference to scrollView's Content Layout Guide
let cGuide = scrollView.contentLayoutGuide
// reference to scrollView's Frame Layout Guide
let fGuide = scrollView.frameLayoutGuide
NSLayoutConstraint.activate([
// constrain stackView to scrollView's Content Layout Guide
stackView.topAnchor.constraint(equalTo: cGuide.topAnchor),
stackView.leadingAnchor.constraint(equalTo: cGuide.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: cGuide.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: cGuide.bottomAnchor),
// constrain stackView's Width to scrollView's Frame Layout Guide
stackView.widthAnchor.constraint(equalTo: fGuide.widthAnchor),
])
这将完全避免需要设置.contentSize
——它将全部由自动布局处理。