Search code examples
iosswiftautolayout

Avoid button height expanding due to other button's height expansion in cell


I have a custom XIB in which I have two buttons which I have pinned to the left and right edges and have added constrains to top, left and bottom for leftButton(named First Button) and top, right and bottom for rightButton(named Second Button)

enter image description here

Now my problem arises when I add padding to the right button(Second Button) only.

Since the left one have top and bottom constraints and adding padding to the right increases the contentSize of the view , so does the leftButton size as well

enter image description here

I checked the height of both the buttons inside the "Debug View Hierarchy" and both are different (left one being smaller and right one being bigger)

enter image description here

What I want to achieve : Increase the height of the rightButton(Second Button) but keep the height of the leftButton(First Button) as is

What I have tried so far :

For leftButton( First Button )

  • I tried changing the "Content Hugging Vertical" priority but it does not makes a difference

  • Reduced the top and bottom constraint's priority from 1000 to 999 so that maybe the height (which is smaller as showing in the debug view hierarchy) will be given the preference

EDIT

Leading margin >=10 failure

enter image description here


Solution

  • Try this:

    • Left Button

      • constrain Leading to superview
      • constrain CenterY to superview
      • constrain Top and Bottom to >= desired value
    • Right Button

      • constrain Trailing to superview
      • constrain CenterY to superview
      • constrain Top and Bottom to >= desired value

    EDIT

    To explain your follow-up question...

    Changing leftButton leading from = 10 to >= 10 does not satisfy auto-layout:

    enter image description here

    Do you want it to be 10? 11? 20? Auto-layout only sees that you want it >= 10.

    If you add a constraint between the buttons:

    enter image description here

    Now we're telling auto-layout: keep 60-pts between the buttons, and at least 10-pts leading for the left button.

    When the right button title gets a little longer:

    enter image description here

    Auto-layout "pushes" the left button to the left, keeping 60-pts between them.

    If we run out of room:

    enter image description here

    Auto-layout still keeps 60-pts between the buttons - by moving left button to the left - but maintains at least (>=) 10-pts leading.

    As you see, though, this will require one of the buttons to compress... so you'll need to give one button a higher Content Compression Resistance Priority than the other so auto-layout knows which one you want to compress.