iOS Top Alignment constraint based on screen (superview) height
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
@IBOutlet
NSLayoutConstraint
2 Answers
2
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
instead of relating the top of the view to the top of the superview relate it to the centerY of the superView and change the multiplier of the constraint
– Sh_Khan
Jul 3 at 7:34
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:
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). This height constraint will update depending on the main view height which will provide the desired visual padding.
Thanks ... Yes i know this padding view solution ... but i was just wondering if same can be achieved without taking extraa views just for padding
– mihir mehta
Jul 3 at 4:39
@mihirmehta Agreed, it's not ideal. If I were implementing this, I would most likely just set this constraint in code rather than adding something like this padding view in the xib. Padding views can be confusing when you try to maintain a section far down the road, constraints in code can be commented for clarity.
– skladek
Jul 3 at 14:27
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Sorry i didn't get the answer ...
– mihir mehta
Jul 3 at 4:39