LoginSignup
6
6

More than 5 years have passed since last update.

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

Posted at

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];

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6