Posted at

コードでAutoLayout中央配置(Objective-C)

More than 3 years have passed since last update.

AutoLayoutのコード設定を覚えるのが面倒なので備忘録。

今回は中央配置。

ex:UILabelを中央配置

//UILabelの作成
UILabel *centerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
centerLabel.text = @"centerLabel";

//autoresizingMaskをoff
[centerLabel setTranslatesAutoresizingMaskIntoConstraints:NO];

//水平値の制約
NSLayoutConstraint *xConstraint = [NSLayoutConstraint constraintWithItem:centerLabel
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0];

//垂直値の制約
NSLayoutConstraint *yConstraint = [NSLayoutConstraint constraintWithItem:centerLabel
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0];

[self.view addSubview:centerLabel];
[self.view addConstraint:xConstraint];
[self.view addConstraint:yConstraint];