LoginSignup
5
9

More than 5 years have passed since last update.

UITabBarController の子 ViewController の初期化

Posted at

概要

UITabBarControllerの子のViewControllerは、自身が表示されるまで初期化されないようなので、自分で初期化処理を呼ぶ必要があります。ここにその方法を書きます。

環境

  • Xcode 8.2.1
  • Swift 3.0.2
  • iOS 10.2

方法

UITabBarControllerのサブクラスを作り、下記のように書きます。


class SampleTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        for vc in self.viewControllers! {
            _ = vc.view
        }
    }
}

これで各ViewControllerの初期化処理(loadView()viewDidLoad())が呼ばれます。StoryboardのCustom class で関連づけるのをお忘れなく。

UITabBarControllerの中でUINavigationControllerを使っている場合は、さらに階層をたどる必要があります。↓はTabBarControllerとNavigationControllerを同時に使う(Storyboard)と同じStoryboardの構成で実装したときの例です。


class SampleTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        for navViewController in self.viewControllers! {
            _ = navViewController.childViewControllers[0].view
        }
    }
}

参考

5
9
2

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
5
9