使用可视格式语言在其父视图中居中视图

Centering a view in its superview using Visual Format Language(使用可视格式语言在其父视图中居中视图)

本文介绍了使用可视格式语言在其父视图中居中视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习适用于 iOS 的 AutoLayout,并了解了 Visual Format Language.

I just started learning AutoLayout for iOS and had a look at Visual Format Language.

这一切都很好,除了一件事:我只是无法让视图在其超级视图中居中.
VFL 可以做到这一点,还是我需要自己手动创建约束?

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?

推荐答案

目前,不,看起来不可能使用 only VFL 在父视图中居中.但是,使用单个 VFL 字符串和单个额外约束(每个轴)并不难:

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}];

我尝试了上述的许多不同变体,试图将其弯曲到我的意愿,但这似乎不适用于超级视图,即使两个轴明确有两个单独的 VFL 字符串(H:|V:).然后,我开始尝试准确地隔离选项确实何时应用于 VFL.它们似乎适用于 VFL 中的超级视图,并且仅适用于 VFL 字符串中提到的任何显式视图(在某些情况下令人失望).

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).

我希望将来 Apple 添加某种新选项以使 VFL 选项考虑到超级视图,即使仅在 VFL 中除了超级视图之外只有一个显式视图时才这样做.另一种解决方案可能是传递到 VFL 中的另一个选项,其内容如下:NSLayoutFormatOptionIncludeSuperview.

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.

不用说,我在尝试回答这个问题时学到了很多关于 VFL 的知识.

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

这篇关于使用可视格式语言在其父视图中居中视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用可视格式语言在其父视图中居中视图

基础教程推荐