IOS8 Autolayout with relative width / height

不羁的心 提交于 2020-04-11 05:09:11

问题


I need to autolayout a storyboard UIView with a single UIControl. The UIControl should be centered, needs to have a aspect ratio of 1:1 and should always use 90% of the superviews width or height depending on the device orientation without clipping.

I added 4 constraints

  1. Center Y Alignment - View - Superview
  2. Center X Alignment - View - Superview
  3. Equal Widths - View - Superview with multiplier set to 0.9
  4. Aspect Ratio - View - View with multiplier set to 1:1

This setup works fine in portrait mode but fails in landscape mode. (See pictures below)

What kind of constraint do i need to solve this problem. Do i have to change the constraints if the device is rotated?

Portrait mode Portrait mode

Landscape mode - wrong Landscape mode - wrong

Landscape mode - mockup. Thats what i want. Landscape mode - ok


回答1:


Here is a way to do it:

  1. Start with the four constraints you list above: Center X, Center Y, Equal Widths (0.9 multiplier), and Aspect Ratio, all with priority 1000.
  2. Change the priority of the Equal Widths to 750. This will allow Auto Layout to ignore or modify this constraint if necessary.
  3. Add an Equal Heights (View - Superview) constraint, but instead of Equal, make it Less Than or Equal with a multiplier of 0.9. Leave its priority at 1000.

Now, when you are in portrait, Auto Layout will be able to satisfy all of your constraints by making the width of the red box to be 90% as before. When you switch to landscape, the Equal Heights constraint will ensure that the red box doesn't grow beyond 90% of the height since this constraint has a 1000 priority, but Auto Layout will also make the box as big as possible in an attempt to best serve the Equal Widths constraint.




回答2:


You forced your view width and your aspect ratio. So when you width grows, autolayout will force your height to grow up too to keep a 1:1 aspect ratio. You have to:

  • Set constraints for your height and width to be <= 0.9* Superview with a 1000 priority
  • Set constraints for your height and width to be == 0.9* Superview with a 750 priority

I didn't try, but it should look better ;)



来源:https://stackoverflow.com/questions/30439214/ios8-autolayout-with-relative-width-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!