My design requires that a button is centered between two other objects. One of the objects is in the vertical center of the view (green). The other object is some distance from the bottom edge (green). Now the task is to center the third object (red) between the other two. I am using xcode6's new constraints and my view is in wRegular hRegular mode. This would be easy with code, but I am trying to use the storyboard to accomplish this.
Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.
Basically if the layout margins are 8,8,8,8 (the default), a constraint with 0 leading space to container margin will have an x position of 8. Note that this is only available on iOS8 or later.
Control-Dragging ConstraintsInterface Builder intelligently selects the set of constraints based on the items you are constraining and the direction of your drag gesture. If you drag more or less horizontally, you get options to set the horizontal spacing between the views, and options to vertically align the views.
There are a number of approaches:
In iOS 9, the easiest would be to define a vertical UIStackedView
with a distribution
of "equal spacing" and then addArrangedSubview
the three circular subviews
Another option in iOS 9 would be to create two UILayoutGuide
(which would represent the two question marks in your image), add them to the shared superview with addLayoutGuide
and define them to be the same size as each other. The corresponding VFL might look like:
"V:|[greenView1(==100)]-[layoutGuide1]-[redView(==50)]-[layoutGuide2(==layoutGuide1)]-[greenView2(==greenView1)]|"
In earlier iOS versions, rather than using UILayoutGuide
, you could just create two "space" views (UIView
with clear background so they're not visible) then define a constraint such that their heights are identical, and then define vertical spacing constraints between the five views (the three circles and the two spacer views) with a constant of zero.
It might look like:
I've made those "spacer" views visible, to illustrate the idea, but obviously you'd set them to be transparent so you can't see them in the UI.
This is logically equivalent to the UILayoutGuide
approach in iOS 9, except that the UIView
"spacer" views just carry a little more overhead than a UILayoutGuide
. But in iOS versions before 9, this is the common approach to this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With