简体   繁体   English

基于屏幕(超级视图)高度的iOS顶部对齐约束

[英]iOS Top Alignment constraint based on screen (superview) height

Let's say for example i want my view's top margin be 比方说,例如,我希望我的视图的上边距为

30 px for iPhone 6s iPhone 6s为30像素

and for the other screen i want to change this constants from 30 to X where X is proportional to total height of screen 对于另一个屏幕,我想将此常数从30更改为X,其中X与屏幕的总高度成比例

ie

36.5 for iPhone X, 33 for iPhone 6s plus, 25 for iPhone SE iPhone X为36.5,iPhone 6s plus为33,iPhone SE为25

And so on .... I know i can take @IBOutlet of NSLayoutConstraint and change it programmatically but what i want is i want to set it like aspect ratio that we have for height width like subview's heigh width is proportional it's superview it changes with super view's height and width 依此类推....我知道我可以采用@IBOutletNSLayoutConstraint并以@IBOutlet方式NSLayoutConstraint进行更改,但我要设置的是像子视图的高度宽度一样的高宽比,它与改变的NSLayoutConstraint视图成比例超级视图的高度和宽度

在此处输入图片说明

The constraint you need here is the superView's centerY set multiplier to 0.5 if you want the top anchor's constant to be 0.25 of screen height from the top , so adjust the multiplier according to this logic which is 如果您希望顶部锚点的常数为距顶部的屏幕高度的0.25,则此处需要的约束是superView的centerY设置乘数为0.5,因此请根据以下逻辑调整乘数

height_of_screen = 2 * centerY 屏幕高度= 2 *中心Y

在此处输入图片说明

This is not possible on just a top constraint like you have. 仅在像您这样的最大约束下这是不可能的。 There isn't a way to associate top distance with height from interface builder. 无法通过界面构建​​器将顶部距离与高度相关联。

You can add a view above your image that only exists to provide that padding. 您可以在图像上方添加仅用于提供填充的视图。 Your hierarchy will look like this in VFL: 您的层次结构在VFL中将如下所示:

"V:|[paddingView][imageView]"

Here's an image of the view in place above the image view: 这是图像视图上方图像的位置:

在图像上方查看

Then you can install a height constraint on that padding view that makes it equal to the containing view. 然后,您可以在该填充视图上安装高度约束,以使其等于包含视图。

使高度相等

Add a multiplier to that constraint that gets you the expected height. 向该约束添加一个乘数,以获取预期的高度。 If you want it to be 30 on a screen that's 667 points tall, then the multiplier will be something like 0.044978 (30 / 667 = ~0.044978). 如果您希望它在667点高的屏幕上为30,那么乘数将为0.044978(30/667 =〜0.044978)。 This height constraint will update depending on the main view height which will provide the desired visual padding. 该高度限制将根据提供所需视觉填充的主视图高度进行更新。

将乘数添加到约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM