erudel
erudel

Reputation: 480

Can AutoLayout equally space multiple buttons?

I am trying to create a view that contains some buttons placed vertically and I would like the spaces between the buttons to be equal when the window is resized. The constraints (using the visual format) on this view are:

H:|-0-[button1]-0-|
H:|-0-[button2]-0-|
H:|-0-[button3]-0-|
H:|-0-[button4]-0-|
V:|-0-[button1]-(>=0)-[button2]-(>=0)-[button3]-(>=0)-[button4]-0-|

The buttons are displayed correctly except that only one of the three spaces defined to be >=0 is taken into account, while the other spaces remain zero (the layout is ambiguous).

Is there a way to set those three spaces to be equal using AutoLayout?

Upvotes: 8

Views: 2832

Answers (3)

David Wong
David Wong

Reputation: 10294

Bridgeyman is right, but I'd like to add.

V:|[button1][spacerView1(>=0)][button2][spacerView2(==spacerView1)][button3][spacerView3(==spacerView1)][button4]|

To be a bit more concise.

You don't need to put 0s in between -s. The same goes with your horizontal spacing

H:|[button1]|
H:|[button2]|
//etc...

Upvotes: 4

bames53
bames53

Reputation: 88215

Instead of using autolayout constraints you should embed the buttons in an NSMatrix that has autoresizesCell set to YES. This will handle the spacing automatically without invisible spacer views.

Upvotes: 3

Bridger Maxwell
Bridger Maxwell

Reputation: 2099

Make invisible views that are between each pair of buttons, and then constrain the width of those views to be equal.

V:|-[button1][spacerView1][button2][spacerView2][button3]-|

Then create a constraint setting the spacerViews to have the same width, and a constraint that the width of the first spacer view should be >=0.

Upvotes: 10

Related Questions