LoginSignup
1
0

More than 1 year has passed since last update.

[Swift]Storyboard生成をコードで1箇所にまとめる

Posted at

はじめに

Storyboardの生成をする時、コードをあちこちに書くことがあると思います。

しかし可視性も悪くなるし
スペルミスの可能性も高まる・・

そこでStoryboardの読み込みを1箇所にまとめると楽です。

Storyboard+.swift
import UIKit

extension UIStoryboard {
  static var firstViewController: FirstViewController {
    UIStoryboard.init(name: "First", bundle: nil).instantiateInitialViewController() as! FirstViewController
  }

  static var secondViewController: SecondViewController {
    UIStoryboard.init(name: "Second", bundle: nil).instantiateInitialViewController() as! SecondViewController
  }

  static var thirdViewController: ThirdViewController {
    UIStoryboard.init(name: "Third", bundle: nil).instantiateInitialViewController() as! ThirdViewController
  }
}

別ファイルでextensionを使います。

呼び出し方

ViewController.swift
let secondVC = UIStoryboard.firstViewController

self.present(secondVC, animated: true, completion: nil)

 
こんな感じで、記述ミスをしにくく簡潔に書けます。

R.Swiftを使えばもう少し楽にできますが、自前でサクッと実装したい時はこっちのがいいかもです。

1
0
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
1
0