How we can increase width of two button when we remove third button from view

416 views Asked by At

I have view with three button with equal size. Each button take 1/3 part portion of view.

Like this image:

enter image description here

If I remove/hide one button then two button width should increase equally and take 1/2 portion of view. if I remove two button then one button size should be equal size of view.

My question is, how it's possible using the Autolayout.

5

There are 5 answers

0
Akhil V Nair On

Best way to do that is to use UISTACKVIEW.Place a stackview and add 3 buttons.You can give proper layout constraints to the stack view as you need

click on stack view-- select attribute inspector change distribution--fill equally spacing--0

Then after that if you hide any button,other buttons will be automatically adjusted in width

1
Sivajee Battina On

Best option is using stackView. StackView gives lots of flexibility in adding or removing items. If you wish to use only auto layouts, you can achieve it by connect it's width constraints as IBOutlet and change the values programatically.

0
EmilioPelaez On

The best way to achieve what you are looking for is, like others have already mentioned, to use a UIStackView.

When the isHidden property of a UIView inside a stack view is set to true, that stack view will hide the view and take care of the layout, so you will only need to set the correct constraints for your stack view.

0
TheCodeTalker On

Other Possible sol to this problem is Adding or removing constraints during runtime is a heavyweight operation that can affect performance. However, there is a simpler alternative.

For the view you wish to hide, set up a width constraint. Constrain the other views with a leading horizontal gap to that view.

To hide, update the .constant of the width constraint to 0.f. The other views will automatically move left to assume position. and for equal width pervoid multiplier to width..

0
Gianluca Tranchedone On

You have a few options:

  1. UIStackView which was made exactly for this.
  2. UICollectionView similar to UIStackView in a certain way, but not really meant for this. However, it does the job nicely and it's easy to implement. Sometimes easier than UIStackView.
  3. NSLayoutConstraint by using multiple constraints with different priority so that you can activate/deactivate them as needed and get the desired result. This approach is a bit more complex by it gives you the highest degree of control and flexibility over the views in your hierarchy.