LoginSignup
95

More than 5 years have passed since last update.

[iOS]viewDidLayoutSubviewsの最後にはlayoutSubviewsを呼び出そう

Last updated at Posted at 2014-01-15

症状

iOSアプリを開発していて、iPhoneシミュレータだとエラーもなく動くのに、実機で動かすとエラーがでた。
エラーの内容は、

Assertion failure in -[UIView layoutSublayersOfLayer:], …

を含むのは共通しているが、その後に続くエラーは様々のようだ。

解決策

これらのエラーは下記コードのように、ViewControllerのviewDidLayoutSubviewsメソッドの最後に、[self.view layoutSubviews]を呼び出すと実機でエラーなく実行できるようになる。
[self.view layoutSubivews]は必ず最後でなければならない。途中で呼び出してもエラーのままである(実体験)。

追記:
[self.view layoutSubview]よりも[self.view layoutIfNeeded]のほうが良さそうなので修正しました。
情報をいただいたtomohisaotaさん、pebble8888@githubさん、usatieさん、ありがとうございました。

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    // レイアウトなどをいろいろいじる
    // …

    [self.view layoutIfNeeded]; // <- これが重要!
}

参考: http://stackoverflow.com/questions/18429728/autolayout-and-subviews

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
95