Search code examples
iosobjective-cautolayout

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.


Solution

  • 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.