I just started learning AutoLayout for iOS and had a look at Visual Format Language.
It all works fine except for one thing: I just can't get a view to center within its superview.
Is this possible with VFL or do I need to manually create a constraint myself?
Add below code and have your button at the center of the screen. Absolutely possible.
For those who came here for an
Interface Builder
based solution (Google leads me here), just add const width/height constraints, and select the subview -> control drag to it's superview -> select "center vertically/horizontally in superview".Instead of using VFL, you can easily do this in interface builder. In the Main Storyboard, ctrl+click on the view you want to center. Drag to the superview (while holding ctrl) and select "Center X" or "Center Y". No code needed.
Absolutely possible was able to do it like this:
Learned this from here. Code above centers subview in view by Y obviously.
Swift3:
What it have to be done is that superview should be declared in the dictionary. Instead of using
|
you use@{@"super": view.superview};
.And
NSLayoutFormatAlignAllCenterX
for vertical andNSLayoutFormatAlignAllCenterY
for horizontal as options.Thanks to the answer from @Evgenii, I create a full example in gist:
center the red square vertically with custom height
https://gist.github.com/yallenh/9fc2104b719742ae51384ed95dcaf626
You can center a view vertically by useing either VFL (which is not quite intuitive) or use constraints manually. By the way, I cannot combine both centerY and height together in VFL like:
In the current solution VFL constraints are added separately.