我认为垂直UIStackView的高度应该是其排列视图的总高度。但是,当我将所有排列视图的帧高度更改为0时,即使调用view.layoutIfNeeded()
,UIStackView的帧高度仍然具有非零值,并且所有排列的视图都消失了。我也尝试将UIStackView的Clip to Bounds
设置为true,但它仍然无效。这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
print("Before --- UIStackView.frame.height: \(stackView.frame.height)")
print("Before --- firstLabel.frame.height: \(firstLabel.frame.height)")
print("Before --- secondLabel.frame.height: \(secondLabel.frame.height)")
print("Before --- thirdLabel.frame.height: \(thirdLabel.frame.height)")
print("Before --- forthLabel.frame.height: \(forthLabel.frame.height)")
for view in stackView.arrangedSubviews {
view.frame = CGRect(x: view.frame.origin.x, y: view.frame.origin.y, width: view.frame.width, height: 0)
}
print("===================================")
print("After --- UIStackView.frame.height: \(stackView.frame.height)")
print("After --- firstLabel.frame.height: \(firstLabel.frame.height)")
print("After --- secondLabel.frame.height: \(secondLabel.frame.height)")
print("After --- thirdLabel.frame.height: \(thirdLabel.frame.height)")
print("After --- forthLabel.frame.height: \(forthLabel.frame.height)")
view.layoutIfNeeded()
}
这是日志:
Before --- UIStackView.frame.height: 82.0
Before --- firstLabel.frame.height: 20.5
Before --- secondLabel.frame.height: 20.5
Before --- thirdLabel.frame.height: 20.5
Before --- forthLabel.frame.height: 20.5
===================================
After --- UIStackView.frame.height: 82.0
After --- firstLabel.frame.height: 0.0
After --- secondLabel.frame.height: 0.0
After --- thirdLabel.frame.height: 0.0
After --- forthLabel.frame.height: 0.0
答案 0 :(得分:1)
我认为您手动使用自动布局和设置框架的混合。要看到一切都按预期工作,而不是设置标签'高度为0的帧将其text
属性设置为空字符串(导致高度为0的intrinsicContentSize
):
// Your print statements BEFORE...
for arrangedSubview in stackView.arrangedSubviews {
if let label = arrangedSubview as? UILabel {
label.text = ""
}
}
view.layoutIfNeeded()
// Your print statements AFTER...
结果:
答案 1 :(得分:0)
使用堆栈视图,您只需隐藏子视图即可调整其高度。
for view in stackView.arrangedSubviews {
view.isHidden = true
}