Auto Layout: Y Position as the Max of Two Values

﹥>﹥吖頭↗ 提交于 2019-12-22 05:16:20

问题


I have a button playButton and to UIViews, myView1 and myView2, whose positions may change during execution. I want the top of playButton to be 10 units below the bottom of UIView1 OR the bottom of UIView2, whichever is the larger value (further down). How would I express this using auto layout in code? I tried setting one constraint as greater or equal but it seemed to have no effect.


回答1:


Here's one way to think about it: create a constraint that the top of playButton is greater than or equal to the bottom of myView1 plus 10, another constraint that the top of playButton is greater than or equal to the bottom of myView2 plus 10, and then a third constraint that the top of playButton be at the top of the shared superview at a low priority.

The two inequalities will make sure the button is below the two views. However, that leaves ambiguity. The button could be anywhere below both. The third constraint can't be satisfied as such, but the auto layout system will try to get as close as possible. This resolves the ambiguity. The button will be as close to the top as possible while still being below both views.

This can actually be simplified. You could sort of combine one of the inequalities with the low-priority equality. Have one constraint that the top of playButton is greater than or equal to the bottom of myView1 plus 10. Have a second constraint that the top of playButton is equal to the bottom of myView2 plus 10, but at a lower priority.

If myView1's bottom is lower than myView2's, then the first constraint requires that playButton be lower than it. The second constraint can't be satisfied, but the system tries to get as close as possible to the bottom of myView2. That keeps the button as high as possible while still being below myView1's bottom. If myView2's bottom is lower than myView1's, then the second constraint determines the position of the button directly. The first constraint is satisfied, too, because it's an inequality.




回答2:


Illustration of KenThomases answer :

view1-> Blue

view 2-> red

view 3-> pink

Constraint between view1 and view 3: Greater than or equal to 20 with priority 1000.

Constraint between view2 and view 3: Equal to 20 with priority 999.

The working is explained by Ken in his answer. Just have a look.

If view 1 is greater than view 2

If view 2 is greater than view 1



来源:https://stackoverflow.com/questions/27892559/auto-layout-y-position-as-the-max-of-two-values

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