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 are 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"@interfaceViewController()@property(nonatomic,strong)UIButton*button;@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];/* 1) Create our button */self.button=[UIButtonbuttonWithType:UIButtonTypeSystem];self.button.translatesAutoresizingMaskIntoConstraints=NO;[self.buttonsetTitle:@"Button"forState:UIControlStateNormal];[self.viewaddSubview:self.button];UIView*superview=self.button.superview;/* 2) Create the constraint to put the button horizontally in the center */NSLayoutConstraint ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access