fxfuture fxfuture - 6 months ago 30
iOS Question

Simplest way to evenly distribute UIButtons horizontally across width of view controller?

I've looked through many answers and they all seem very complex! Most recently I was looking at this answer although I'd prefer not to have to put my buttons inside views.

I have 6 UIButtons that are all the same dimensions. I want to space them evenly horizontally across the full width and at the bottom of my root view controller.

| |
| |
| [b1] [b2] [b3] [b4] [b5] [b6] |
________________________________________


What is the simplest way to achieve this programmatically?

Answer

I think this is simpler than the link on the accepted answer. Ok, firstly lets create some buttons:

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.translatesAutoresizingMaskIntoConstraints = NO;
[button1 setTitle:@"Btn1" forState:UIControlStateNormal];

... do that 6 times for 6 buttons, however you like then add them to the view:

[self.view addSubview:button1];
[self.view addSubview:button2];
[self.view addSubview:button3];
[self.view addSubview:button4];
[self.view addSubview:button5];
[self.view addSubview:button6];

Fix one button to the bottom of your view:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];

Then tell all the buttons to be equal width and spread out equally across the width:

NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2, button3, button4, button5, button6);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button1][button2(==button1)][button3(==button1)][button4(==button1)][button5(==button1)][button6(==button1)]|" options:NSLayoutFormatAlignAllBottom metrics:nil views:views]];

Result:

enter image description here

Comments