3

I have a UIView with 3 UIButtons and what I want is when I hide one button I want other two buttons to centrally aligned with equal margin. Let say if there are 3 buttons the UI should be Like

If there are 3 buttons
---------------
[   ][   ][   ]
---------------

if I hide Middle button

---------------
  [   ][   ]
---------------


if I hide 2 buttons
---------------
     [   ]
---------------

is it possible using auto layout ? If yes then please guide in right approach.

Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256

3 Answers3

2

Just Check out accepted answer of @Usama : Align Three UIButton using Auto Layout

Here is the Sample Code

Sample code output:

Sample code output

Thanks to : Usama

Community
  • 1
  • 1
P R J
  • 428
  • 5
  • 18
0

One approach is to add width constraint to every button and set its constant and leading constraint constant to zero when the corresponding button is hidden.

Another approach is to remove unnecessary constraints and add new constraints on every change.

You should remember that hidden views still acts in autolayout process.

kirander
  • 2,202
  • 20
  • 18
0

Most things are possible with Auto Layout, but not always easy.

Here's what I would try (I'm focusing here on just the horizontal arrangement - you will of course need to add constraints for vertical arrangement but that should be easy):

  1. Create a UIView to act as a container to hold the buttons.
  2. Constrain this container view to center horizontally within your main view.
  3. Position your 3 buttons inside the container view: a. Set width constraints on all the buttons. b. Constrain first button leading to container leading. c. Constrain first button trailing to second button leading with however much spacing you want. d. Constrain second button trailing to last button leading with same spacing as in c. e. Constrain last button trailing to container trailing.
  4. Create outlets for the button width constraints and the spacing constraints c. and d. above.

Now, to hide any button, set its width constraint constant to 0 and its nearest spacing constraint to 0. (The middle button has spacing constraints on either side - pick one to set to 0, it does not matter which one.)

To redisplay a button, set the constraint constants back to their original values.

Mike Taverne
  • 9,156
  • 2
  • 42
  • 58