我有一个自定义视图,它是一个带有堆栈视图的滚动视图。我在这个堆栈视图中添加了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
最后,当我使用调试视图层次结构时,我确实可以看到scrollingSV的高度和宽度,以及容器内部的视图。
下面是我试图获取scrollingSV大小的代码,它返回0:
print("Scrollview height: \(scrollingSV.contentSize.height )")
我已经尝试通过使用union来获取内容大小,如堆栈溢出答案中所述:How do I auto size a UIScrollView to fit its content,但这也返回0。
我怎样才能得到这个滚动堆栈视图的大小?或者它还没有在viewDidLoad中计算?
谢谢
发布于 2020-04-28 11:03:56
显然,在viewDidLoad中,视图并没有完成它们的子视图布局。所以高度还没有意义。
当我在viewDidAppear中做这个检查时,这个问题已经解决了,我可以达到滚动堆栈视图的contentSize和框架高度。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
scrollingSV.isScrollEnabled = scrollingSV.contentSize.height > scrollingSV.frame.height
}
https://stackoverflow.com/questions/61364283
复制