【问题标题】:How to programmatically determine the height of UIStackView after a subview has been hidden swiftswift - 隐藏子视图后如何以编程方式确定UIStackView的高度
【发布时间】:2018-09-13 11:14:16
【问题描述】:

我在 UIScrollView 中使用 UIStackView,我想确定堆栈视图的高度,以便我可以通过编程方式调整滚动视图的高度以适应隐藏子视图的情况。

我正在使用

stackView.frame.height 

确定堆栈视图高度。这在viewDidLoad() 中调用,但无论子视图是否隐藏,它始终是故事板中相同的高度值。

如何确定身高?

【问题讨论】:

  • viewDidLoad 为时过早。试试viewDidAppear

标签: ios swift uiscrollview uistackview


【解决方案1】:

对任何视图进行布局更改后,它必须在功能完成后重新计算其框架。要立即获取更新的框架,请调用:

stackView.layoutIfNeeded()

例子:

print(stackView.frame.height) // old height
subview1.isHidden = true
print(stackView.frame.height) // still old height
stackView.layoutIfNeeded()
print(stackView.frame.height) // new height

更多详情请见the documentation

【讨论】:

  • 感谢回答,.layoutIfNeeded() 后我仍然收到旧高度。
  • @Khoury 您是否尝试过完全移除排列好的子视图(不仅仅是隐藏它)以查看是否会改变高度?
  • 我刚才把它从隐藏改成了.removeFromSuperview(),高度还是没有变化?
  • @Khoury 你需要调用setNeedsLayout() 之前 .layoutIfNeeded(),然后得到框架高度。
  • @Khoury 而不是 removeFromSuperview() 尝试stackview.removeArrangedSubview(subview1)
猜你喜欢
  • 2021-04-23
  • 2011-08-10
  • 2021-04-26
  • 2017-09-10
  • 1970-01-01
  • 2017-12-29
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多