简体   繁体   中英

How do I specify a spacing constraint as a proportion of the superview's size?

Say I have an image view and I want its width to be equal to half of the superview's width. I can add an "Equals Width" constraint between the image view and the superview, using a multiplier of 0.5.

Similarly, I'm looking for a way to specify a spacing constraint as a proportion of the superview's size. Continuing with the example above, instead of wanting the width of the image view to be half of the superview's, I would, for instance, want the distance between the bottom of my image view and the bottom layout guide to be a fifth of the superview's height.

Here is one solution that has worked for me in the past. It feels like a bit of an odd way to do it, but it will do the trick.

First, put five hidden views in your superview that are of equal heights. Be sure to use constraints to make these expand and contract with their superview. Now no matter what size your superview is, you will have these views inside of it that are exactly one fifth of your superview's size.

在此处输入图片说明

To use the example from your question, now you can constrain your imageView's size to be proportional to one of those five hidden views. Then you can constrain it to be centered to one of them so your spacing will also be appropriate for any size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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