Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AutoLayout equally space multiple buttons?

Tags:

cocoa

osx-lion

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?

like image 890
erudel Avatar asked Nov 28 '11 17:11

erudel


3 Answers

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.

like image 130
Bridger Maxwell Avatar answered Nov 14 '22 10:11

Bridger Maxwell


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...
like image 44
David Wong Avatar answered Nov 14 '22 09:11

David Wong


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.

like image 27
bames53 Avatar answered Nov 14 '22 08:11

bames53