2
votes

I wondered how to use constraints to center an object between two others vertically. I use storyboards. The label and the button have constraints using autolayout (label: top, leading, trailing, height; button: bottom, leading, trailing, aspect ratio).

Here is how all that looks like:

Here is a schematic of my UI.

I want constraint 1 and 2 (take a look at the image) to be the same length so that 'view' is vertically centered between 'label' and 'button'. Placing hidden views with the same height in between didn't work for me in smaller screen sizes. Thank you!


PS: One important thing is: I want the view to be centered and not all elements equally spaced!

2
Nishant answer works well even for the variable label & button sizes. but in your case label and button has constant height. so adding vertical center constraint, then adjusting it's constant to match center will do the trick. In this case constant value = (label top space + height) - (button bottom space + height) / 2. In this way you can avoid one extra view.Surya Subenthiran

2 Answers

7
votes

Take a transparent view with top constraint 0 to topView(lable) and bottom constraint 0 to bottom view(Button). Now add the view in that view which you want vertically centre to both view. And add it constraints as horizontal and vertical centre to the parent view.

4
votes

You can try stackview here. Put all items in to stack view and provide equal spacing