StackView返回viewDidLayoutSubviews中的前高度



所以我有一个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,我的stackViewHeight500

当我的onHitButton被调用时,我的[label1,2,3].isHidden = false,我的stackViewHeight仍然是500,但屏幕显示正确,那些labels现在可见,我的stackView被拉伸。当然,我的scrollView不能正确显示。

然后我再次点击我的onHitButton,那些labels被隐藏,我的stackView在屏幕上收缩,但stackViewHeight返回850?

应该是相反的。

我还试图在另一个button调用上printheight,它返回正确的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——它将全部由自动布局处理。

最新更新