【问题标题】:How to get a custom scrollingStackView's height如何获得自定义滚动 StackView 高度
【发布时间】:2020-08-05 10:10:51
【问题描述】:

我有一个自定义视图,它是一个带有堆栈视图的滚动视图。我在这个堆栈视图中添加了 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 )")

我已经尝试通过使用联合来获取内容大小,如此 stackoverflow 答案中所述:How do I auto size a UIScrollView to fit its content 但这也返回 0。

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

谢谢

【问题讨论】:

  • 不,viewDidLoad() 中未确定大小。您可以在viewDidLayoutSubviews 中尝试,但如果正确设置了约束,您不需要进行任何高度计算。但是,您的布局不是很清楚...也许编辑您的问题并包含屏幕截图。

标签: swift uiscrollview size frame uistackview


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多