简体   繁体   中英

Auto Layout: Y Position as the Max of Two Values

I have a button playButton and two 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.

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.

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

在此处输入图片说明

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