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

后端 未结 3 1361
暗喜
暗喜 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条回答
  •  庸人自扰
    2020-12-24 03:58

    I've faced the same issue while trying to vertically center a label inside a scrollView when the label does not fill the scrollView (top aligned otherwise) and found an as simple solution as it is dirty, all in IB with no extension or sub-classing.

    First of all, set the usual contraints when dealing with a UIScrollView:

    1. Top, bottom, leading, trailing child view constrained to the scrollView content layout guide
    2. Child view width equal to the scrollView width

    Then make the child view's height greater or equal to the scrollView height (it triggers a constraint error). Now set this constraint multiplier to anything close to 1 but not quite (eg. 0.999999). The constraint error disappears and the child view behaves as expected.

    Not proud of this one but it could save some time to people in a rush.

提交回复
热议问题