Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
346 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...