Center UIView vertically in scroll view when its dynamic Labels are small enough, but align it to the top once they are not

后端 未结 3 1357
暗喜
暗喜 2020-12-24 03:24

I have a view with 3 dynamic labels inside it and I am trying to find a way to centre it vertically in a scroll view but when its dynamic labels are too large to fit on a pa

3条回答
  •  Happy的楠姐
    2020-12-24 04:04

    To add on to DonMag's answer, you can actually accomplish the exact same thing by using only the UIScrollView and UIStackView. This is for iOS 11 and above as it uses the contentLayoutGuide and frameLayoutGuide properties on UIScrollView.

    When I refer to scroll view's content view, it simply means the scrollable content layout area within the scroll view. It refers to the content layout guide, not the stack view.

    The steps are as follows, written in pseudocode (just add the equivalent constraints):

    1. scrollView.contentLayoutGuide.height >= scrollView.frameLayoutGuide.height - This sets up the scroll view content to be at least as tall as the scroll view itself. By doing this on its own, we aren't able to center the content just quite yet.
    2. stackView.centerY == scrollView.contentLayoutGuide.centerY - This will force the stack view to be centered vertically with the scroll view content view. But wait, what if the stack view is too short? Remember in step 1, we forced the content size to be at least as tall as the scroll view itself. This means that if the stack view is not tall enough to cause scrolling, it will actually center itself within the content view, which is as tall as the scroll view, causing the desired effect.
    3. stackView.top/bottom <= (inside) scrollView.contentLayoutGuide.top/bottom - This just sets the stack view's edges so that the top and bottom are within the scroll view's content view.
    4. (optional) stackView.top/bottom == (inside) scrollView.contentLayoutGuide.top/bottom with defaultLow priority - This forces the scroll view's content view to have intrinsic height in the cases where your view debugger complains.

    This should be sufficient for vertical constraints. Add your necessary horizontal constraints, and everything should be good to go!

提交回复
热议问题