3.1. Placing UI Components in the Center of the Screen
Problem
You want to be able to place a UI component in the center of the screen. In other words, you want to place a view at the center of its superview, using constraints.
Solution
Create two constraints: one to align the center.x position of the target view on its superview’s center.x position, and the other to align the center.y position of the target view on its superview’s center.y position.
Discussion
Let’s get started by first creating a simple button, which we will align at the center of the screen. As mentioned in the Solution section of this recipe, all we have to do is make sure the x and the y of the center of our button is the same as the x and y of the center of the view on which the button resides. So for this, we will create two constraints and add them to the view that owns the button, called the superview of the button. Here is the simple code that will achieve this:
#import "ViewController.h"
@interface
ViewController
()
@property
(
nonatomic
,
strong
)
UIButton
*
button
;
@end
@implementation
ViewController
-
(
void
)
viewDidLoad
{
[
super
viewDidLoad
];
/* 1) Create our button */
self
.
button
=
[
UIButton
buttonWithType:
UIButtonTypeRoundedRect
];
self
.
button
.
translatesAutoresizingMaskIntoConstraints
=
NO
;
[
self
.
button
setTitle:
@"Button"
forState:
UIControlStateNormal
];
[
self
.
view
addSubview:
self
.
button
];
UIView
*
superview
=
self
.
button
.
superview
;
/* 2) Create the constraint to put the button horizontally in the center */
NSLayoutConstraint ...
Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.