おーしまブログ

プログラミングやってます

【最新swift5】別のstoryboardへの画面遷移

こんにちは、おーしまです。

今回は、swiftで別のstoryboardへ画面遷移する方法について書きます。




例えば今回は、
Main.storyboardからOther.storyboardのOtherViewControllerへ遷移するとします。

下のコードは、モーダル遷移のフルスクリーン表示です。


//stortboardを指定
let storyboard:UIStoryboard = UIStoryboard(name: "Other", bundle: nil)
//ViewControllerをインスタンス化
let viewController = storyboard.instantiateViewController(identifier: "OtherViewController") as! OtherViewController
//NavigationControllerを指定
let nav = UINavigationController(rootViewController: viewController)
//モーダル遷移が画面全体になるように指定
nav.modalPresentationStyle = .fullScreen
//遷移
present(nav, animated: true)



まずは、遷移したいstoryboardを
UIStoryboard(name: "Other", bundle: nil)
で指定します。



次に、そのstoryboardの中の、ViewControllerをインスタンス化します。
f:id:tomo_bb_aki0118115:20210701230730p:plain:w200:h200



storyboardで「Storyboard ID」のところで名前を決めておいて、
storyboard.instantiateViewController(identifier: "OtherViewController")
のidentifierは「Storyboard ID」と同じ名前にします。



as! OtherViewControllerで、OtherViewControllerクラスのインスタンスになります。



今回は、モーダル遷移した後に、push遷移したいのでNavigationControllerを指定して、.fullScreenしていますが、
ただのモーダル遷移なら、


//stortboardを指定
let storyboard:UIStoryboard = UIStoryboard(name: "Other", bundle: nil)
//ViewControllerをインスタンス化
let viewController = storyboard.instantiateViewController(identifier: "OtherViewController") as! OtherViewController
//モーダル遷移
present(viewController, animated: true, completion: nil)

これだけで十分です。







push遷移は最後を変えるだけです。


//stortboardを指定
let storyboard:UIStoryboard = UIStoryboard(name: "Other", bundle: nil)
//ViewControllerをインスタンス化
let viewController = storyboard.instantiateViewController(identifier: "OtherViewController") as! OtherViewController
//push遷移
navigationController?.pushViewController(viewController, animated: true)


今回はここまでです。
それでは、また

ここはどこ おれはだれ それに近いものがあんだよ 始めようとした奴らも迷い始めてる 怖がらせないでよ そりゃ甘くはないけど まだまだ 夢見ていい世界なんでしょ {UVERwould「ハイ!問題作」}