ioslayoutautolayoutvisual-format-language

Centering a view in its superview using Visual Format Language


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?


Solution

  • Currently, no, it doesn't look like it is possible to center a view in the superview using only VFL. It is, however, not that difficult to do it using a single VFL string and a single extra constraint (per axis):

    VFL: "|-(>=20)-[view]-(>=20)-|"

    [NSLayoutConstraint constraintWithItem:view
                                 attribute:NSLayoutAttributeCenterX
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:view.superview
                                 attribute:NSLayoutAttributeCenterX
                                multiplier:1.f constant:0.f];
    

    One would think that you would simply be able to do this (which is what I initially thought and tried when I saw this question):

    [NSLayoutConstraint constraintsWithVisualFormat:@"|-(>=20)-[view(==200)]-(>=20)-|"
                                     options: NSLayoutFormatAlignAllCenterX | NSLayoutFormatAlignAllCenterY
                                     metrics:nil
                                       views:@{@"view" : view}];
    

    I tried many different variations of the above trying to bend it to my will, but this does not appear to apply to the superview even when explicitly having two separate VFL strings for both axes (H:|V:). I then started to try and isolate exactly when the options do get applied to the VFL. They appear to not apply to the superview in the VFL and will only apply to any explicit views that are mentioned in the VFL string (which is disappointing in certain cases).

    I hope in the future Apple adds some kind of new option to have the VFL options take into account the superview, even if doing it only when there is only a single explicit view besides the superview in the VFL. Another solution could be another option passed into the VFL that says something like: NSLayoutFormatOptionIncludeSuperview.

    Needless to say, I learned a lot about VFL trying to answer this question.