Search code examples
iosxcode6.1autolayoutios-autolayout

Autolayout constraint issue when device orientation gets changed


enter image description here

I am facing an issue in auto layout. I want two buttons as shown in screenshot. I want them to show correctly in landscape mode also.

1) Buttons should be centre align horizontly.

2) Buttons should have equal width and height.

3) Button should have equal distance from the superview’s centre vertically in both orientation (landscape and portrait)

I am having issue with condition 3rd. I want UI to be uniform on all size of devices in both orientation.

Is it possible to achieve this using auto layout or I need to update the constraints on orientation change?

I was thinking to add another view in superview’s centre and apply the following constraints with that view to achieve the desire UI

1) Add another transparent view of size (superview’s width, 1)

2) Add horizontal and vertical centre alignment constraint to the newly added view.

3) Add all the required constraints for newly added view like width, height and x position.

Now just the two button like this

4) Add bottom space constraint to button 1 with newly added view 5) Add top space constraints to button 2 with newly added view

So that this will remain same in all orientation and all size of devices.

This approach is not good as we need to add extra view. Please suggest if someone has better approach/idea


Solution

  • I think the best practical solution is embedded your buttons in a view.

    So reset all your constraints. Select your two buttons and embed them in a view:

    After that set this view align always in center:

    At this point you need to set:

    • height and width for your buttons
    • distance between buttons
    • height and width for your view:
      • height = (height of buttons + distance between buttons)
      • width = width of buttons
    • set top and bottom constraints for buttons, so they can be fitted to view; for example for top button:

    This is my final result:

    iPhone 6 portrait:

    and landscape: