ViewControllerをStoryboardから生成する
複数人で一つのアプリを開発する場合Storyboardのコンフリクトを避けるために1画面1Storyboardで作ることがあります。 ※その場合でも関連する画面がある場合は1つのStoryboardの中に複数の画面を作る場合もあります。
このような作り方をした場合、同名のStoryboardとUIViewControllerを作成してViewControllerをStoryboardから取得する生成する形になります。
その度に同じようなコードを書くのが面倒なので記述しすることとします。
ViewControllerのクラス名を取得 その名前を使ってUIStoryboardのインスタンスを生成 UIStoryboardのinstantiateInitialViewControllerメソッドでViewControllerを生成 という処理を記述しています。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol StoryboardInitializable { | |
} | |
extension StoryboardInitializable where Self: UIViewController { | |
static func instantiateStoryboard() -> Self { | |
let type = Mirror(reflecting: self).subjectType | |
let name = String(describing: type).components(separatedBy: ".")[0] | |
let storyboard = UIStoryboard(name: name, bundle: nil) | |
let viewController = storyboard.instantiateInitialViewController() as! Self | |
return viewController | |
} | |
} |
同名のStoryboardとUIViewControllerを作成していること、Is Initial View Controllerにチェックを入れていることが前提になっているのでご注意ください。
実際の使い方はこちら。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ViewControllerのクラスをStoryboardInitializableプロトコルに準拠させる | |
class IkujiLogInputViewController: UIViewController, StoryboardInitializable { | |
// hoge〜 | |
} | |
// ViewControllerを取得して表示させる(別のViewControllerで記述する) | |
let vc = IkujiLogInputViewController.instantiateStoryboard() | |
present(vc, animated: true, completion: nil) |