mzgkworks

iOSを中心にプログラミング関係について書く

【Objective-C】コードでAutoLayoutを指定する場合の注意点(The view hierarchy...)

WKWebViewなどのStoryBoard上で設定できないViewに対しては、コードでAutoLayoutを設定する必要がある。
その際に、注意しないと実行時に「The view hierarchy is not prepared for the constraint:〜」が出力される。
ビルド時にはエラーやワーニングは吐かれず、実行時にひっそりとXcode下部のコンソールペインに以下が出力される。

The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x16d67820 WKWebView:0x16e5a5c0.width == UIView:0x16e5a360.width>
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved 
before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.

環境

XCode6.1.1
iOS8
Objective-C

対応方法

これは感覚的にやってしまう、以下の処理順で発生する。

  1. Viewのインスタンスを生成
  2. ViewのAutoLayoutを設定
  3. Viewを配置

対処としては、2と3の順番を逆(配置した後にAutoLayoutの設定)にすること。

  1. Viewのインスタンスを生成
  2. Viewを配置
  3. ViewのAutoLayoutを設定