LoginSignup
5
4

More than 5 years have passed since last update.

Storyboard/xib から生成した ViewController を NavigationController 下にホストする

Posted at

Storyboard/xib から NavigationController にホストされた ViewController を作りたい場合、Storyboard 上で先に NavigationController をホストする方法もありますが、この場合、自分で作った ViewController に変数を渡したい時が面倒です。

・Storyboard 上で NavigationController にホストされた ViewController の例
スクリーンショット 2015-10-18 18.12.46.png

そこで、Storyboard 上には Navigation Controller を生成せず、コードで NavigationController を追加します。

・ViewController のみを定義
スクリーンショット 2015-10-18 18.15.36.png

let vc = UIStoryboard(name: "Main", bundle:nil).instantiateViewControllerWithIdentifier("storyboardId") as! UIViewController
vc.some_variable = xxx // ここで変数を渡す
let navigationVC = UINavigationController(rootViewController: newsVC) // navigation controller にホストさせる

これで NavigationController にホストされた ViewController に変数を渡しやすくなりました。

おまけ - 生成した ViewController を Tab の一部にする

この生成した NavigationController を Tab の一部にしたい場合、 tabBarItem を設定してあげると Tab 中にアイコン・名称が表示されるようになります。

vc.tabBarItem = UITabBarItem(title: "ニュース", image: UIImage(named: "News"), tag: 0)

このように表示されるようになります。

スクリーンショット 2015-10-18 18.20.26.png

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