こんにちは、おーしまです。
今回は、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をインスタンス化します。
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)
今回はここまでです。
それでは、また