Jian Jie
Jian Jie

Reputation: 289

Equal width and equal spacing between buttons in autolayout

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:

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?

Upvotes: 23

Views: 13159

Answers (4)

Marek R
Marek R

Reputation: 37697

Finally I have oblivion how to solve this problem. I've test it works like charm.

  1. add constraints to space items with 20 units margin
  2. add constraint to ages
  3. now tricky part
    • for each item add constraint equal widths to a parent
    • select all this new constraints and change its properties
    • set multiplier to value 1:5
    • set constant to -24 (6 separation between items and parent edge gives 120, this multiplied by multiplier value 1:5 gives 24)
    • update items frames

That's it! Picture below show how it works in interface builder:

interface builder result

Set simulated size to "freeform" and test different widths (I sett this to 330).

Upvotes: 4

dobranoc
dobranoc

Reputation: 475

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)

Upvotes: 16

B H
B H

Reputation: 111

In the interface builder you set the spacing constraints between buttons like you described above. Then you can command-select all of them and specify the "Equal Width" constraint to apply to the selected objects.

Upvotes: 7

iHulk
iHulk

Reputation: 4909

This problem is seems to be because of wrong content hugging priority and content compression Resistance priority. So you should set them as low content hugging and high compression resistance (all should have same value).

Because content hugging is the property that resist a view to grow and content compression Resistance priority is to resist a view to shrink. For more information regarding these you can found this Question.

Upvotes: 3

Related Questions