如何获得自定义滚动 StackView 高度

How to get a custom scrollingStackView's height

我有一个自定义视图,它是一个带有堆栈视图的滚动视图。我在这个堆栈视图中添加了 3 个容器视图以垂直堆叠和滚动。在每个容器视图中,我添加一个 UIImage 或一个 UILabel 视图。

如果所有视图都已在屏幕上可见,我不希望我的滚动视图滚动。 为此,我需要知道我的 scrollingStackView 的高度,以便我可以将它与当前屏幕尺寸进行比较。 这是我在 viewDidLoad 中设置它们的方式:

setupScrollingSV()

setupContainer1()
setupContainer2()
setupContainer3()

setupImageViewInContainer1()
setupImageViewInContainer2()
setupLabelViewInContainer3()

我的自定义滚动堆栈视图没有大小,我以编程方式对其进行布局,提供左、右、上锚点。

scrollingSV.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
scrollingSV.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
scrollingSV.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true

在我的视图的安全区域中还有另一个堆栈视图,它有这个滚动堆栈视图和另一个容器视图 ContainerView4。

我这样布局 ContainerView4:

ContainerView4.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
ContainerView4.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
ContainerView4.topAnchor.constraint(equalTo: scrollingSV.bottomAnchor).isActive = true
ContainerView4.bottomAnchor.constraint(equalTo: stackView.bottomAnchor).isActive = true
ContainerView4.heightAnchor.constraint(equalToConstant: 100.0).isActive = true

最后,当我使用调试视图层次结构时,我确实看到了我的滚动 SV 的高度和宽度,以及容器内的视图。

这是我试图获取 scrollingSV 大小的代码,returns 0:

print("Scrollview height: \(scrollingSV.contentSize.height )")

我已经按照这个 Whosebug 答案中的说明尝试使用 union 来获取内容大小:How do I auto size a UIScrollView to fit its content 但这也是 returns 0.

如何获取此滚动堆栈视图的大小? 还是viewDidLoad中还没有计算?

谢谢

显然在 viewDidLoad 中,视图尚未完成其子视图的布局。所以高度还没有意义。

当我在 viewDidAppear 中执行此检查时,问题已解决,我可以到达滚动堆栈视图的 contentSize 和框架高度。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    scrollingSV.isScrollEnabled = scrollingSV.contentSize.height > scrollingSV.frame.height
  }