Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal width and equal spacing between buttons in autolayout

Tags:

I'm trying to use autolayout constraints to automatically resize a few similarly-sized buttons in a view to give the following effect:

Before resizing

Before stretching

Desired effect after resizing

After stretching

As you can tell, I want the buttons to be of the same size and I also want the spacing between each button to be a constant 20 points. It seems pretty simple at first, so I set the following constraints:

  • Buttons: space from left neighbour = 20 (inclusive of left-most and right-most buttons)
  • Buttons: space from right neighbour = 20 (inclusive of left-most and right-most buttons)
  • Buttons: same width

What actually happens after resizing

enter image description here

When in preview or when I test run the app in my iPhone/simulator, the button resizes and doesn't even follow the same width constraint I set for it. In fact, the view containing the views also resizes to fit the new button sizes. Anyone knows how to fix this problem purely in the interface builder?

like image 637
Jian Jie Avatar asked Oct 04 '14 12:10

Jian Jie


People also ask

How do you add equal width constraints?

To add equal width constraint, you will need to select both views by command clicking on both of them. Then click on the pin menu and the previously grayed out Equal Width checkbox is now available. Click on that and click Add 1 Constraint.

What is Autolayout aspect ratio?

If you select Aspect Ratio for multiple items, Auto Layout chooses the width of one of the items for the numerator and the height of another item for the denominator. To change the initial aspect ratio, edit the Multiplier field of the Attributes inspector for the constraint.

What is multiplier in Autolayout?

Multiplier is there for creating Proportional Constraint. Auto Layout calculates the first item's attribute to be the product of the second item's attribute and this multiplier . Any value other than 1 creates a proportional constraint.

What is Autolayout in Swift?

Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.


1 Answers

Setting:
- equal widths of all buttons
- horizontal spacing between all buttons
- leading to superview for the first button and trailing to superview for the last button
should do the job. Unless you're having problems with the superview (e.g. ScrollView missing constraints)

like image 127
dobranoc Avatar answered Sep 28 '22 03:09

dobranoc