Mihir Mehta
Mihir Mehta

Reputation: 13833

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

and for the other screen i want to change this constants from 30 to X where X is proportional to total height of screen

i.e.

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

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

enter image description here

Upvotes: 1

Views: 1886

Answers (2)

Sean Kladek
Sean Kladek

Reputation: 4446

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:

"V:|[paddingView][imageView]"

Here's an image of the view in place above the image view:

view above image view

Then you can install a height constraint on that padding view that makes it equal to the containing view.

make heights equal

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). This height constraint will update depending on the main view height which will provide the desired visual padding.

add multiplier to the constraint

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

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

height_of_screen = 2 * centerY

enter image description here

Upvotes: 6

Related Questions