NavigationControllerの画面遷移で、ストーリーボードの黄色丸からドラックする方法ではなく、コードのみを用いて遷移する方法。
準備
・遷移元Viewcontroller、遷移先NextViewControllerを用意する。
・ViewControllerのみEnbed in NavigationControllerをする。
・ViewControllerに画面遷移するためのボタンを用意する。

1. 遷移先のNextViewControllerにStoryBoarIDを設定する。
今回は「next」とした。
またUse StoryBoardIDにチェックを入れる。

2.遷移元ViewControllerにコードを書く。
遷移するためのボタンをIBActionで繋いで、その中にStoryBaordIDから遷移先を取得し、push遷移するための記述をする。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func button(_ sender: Any) {
//遷移先のNextViewControllerを取得
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "next") as! NextViewController
//画面遷移をする
navigationController?.pushViewController(nextVC, animated: true)
}
}
※「as! NextViewController」のところを遷移先のController名にするのを忘れがちなので注意!
3. 遷移先NextViewControllerにコードを書く。
NavigationBarを表示させ、タイトルを設定するための記述をする。
import UIKit
class NextViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//NavigationBarを表示する
navigationController?.setNavigationBarHidden(false, animated: false)
//遷移先のタイトルを設定する
self.navigationItem.title = "タイトル"
}
}
4. 完成
