Auto Layout in iOS 6: Centering Views

iOS 6 brings a new feature to design your user interface: Auto Layout. With Auto Layout you can layout the views in code using constraints. If you are new to this concept then check out this introductionary tutorial. In this tutorial we will create a button and center this on the main view using constraints.

Open Xcode and create a new Single View Application. For product name, use CenteringViewsDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

In ViewController.m in the interface section declare the following properties.

@interface ViewController ()

@property (nonatomic, strong) UIButton *centerButton;

@end

We will set constraints on this buttons so it will be placed centered on the main view.

Change the viewDidLoad method to

- (void)viewDidLoad
{
[super viewDidLoad];

self.centerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.centerButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.centerButton setTitle:@"Center" forState:UIControlStateNormal];
[self.view addSubview:self.centerButton];

NSLayoutConstraint *constraint = [NSLayoutConstraint
constraintWithItem:self.centerButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f];

[self.view addConstraint:constraint];

constraint = [NSLayoutConstraint
constraintWithItem:self.centerButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0.0f];

[self.view addConstraint:constraint];
}

We initialize a button with the text "center" on top. The translatesAutoresizingMaskIntoConstraints property is set to NO to disable the old "springs and struts" method. We define two constraints to center the button on the x- and y-axis.

Build and Run, the button is centered on the main view.

You can download the source code of the CenteringViewsDemo at the ioscreator repository on github.