Last Updated: February 25, 2016
·
23.99K
· novalagung

iOS - Centering view vertically and horizontally using autolayout programmatically

Centering a view using Auto Layout constrains via GUI builder is easy as drinking water. Here some example how to do that programmatically:

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

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

source : http://stackoverflow.com/a/21494707/1467988