Objective-CでコードからAutoLayoutを設定する


参考

iOS 9で追加されたNSLayoutAnchor使うと簡単にわかりやすく間違えずにNSLayoutConstraint(制約)が作れます【Auto Layout】

目的

HowTo目的なので、細かな仕様は参考記事を見てください。
参考記事の言語はswiftですが、Objective-Cでもほぼ同じです。
その内のほぼ同じ でない 部分をぱっとみてコーディングできるように備忘録です。

サンプル

Objective-C
// 今回生成し制約を設定したいview
// 制約でサイズを決めるのでCGRectZeroでOK
UILabel* label = [[UILabel alloc] initWithFrame:CGRectZero];
// AutoResizingはNOにする
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
// viewにaddする
[self.view addSubview:label];

// 上
NSLayoutConstraint* topAnchor = [label.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:0];
// 左
NSLayoutConstraint* leftAnchor = [label.leftAnchor constraintEqualToAnchor:self.view.leftAnchor constant:0];
// 右
NSLayoutConstraint* rightAnchor = [label.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:0];
// 高さ
NSLayoutConstraint* heightAnchor = [label.heightAnchor constraintEqualToConstant:60];
[self.view addConstraint:topAnchor];
[self.view addConstraint:leftAnchor];
[self.view addConstraint:rightAnchor];
[self.view addConstraint:heightAnchor];

気をつけるところ

基本的な考え方

  1. 高さ
  2. 下 の順で組み立てていくと理解しやすい。

translatesAutoresizingMaskIntoConstraintsはNOにする

これをしないと勝手にリサイズされて意図したものにならない。

制約をaddConstraintするタイミングと場所

  • addConstraintするのは親ViewにaddSubViewsした後に行う
  • addConstraintするのは今回生成し制約を設定したいviewに行うのではなく、 addSubViewsした親Viewに対して 行う

所感

SwiftだとisActive=trueだけで済んでいたのでaddConstraintの曲がった感じが気持ち悪い。
まだ親viewに対してaddConstraintするあたりも同様。
更に言うならleftAnchor→leadingAnchor、rightAnchor→trailingAnchorなどの命名も日本人には馴染みがなく手間がかかって面倒。