Skip to content

Instantly share code, notes, and snippets.

@M-Miyazako
Created February 6, 2020 07:39
Show Gist options
  • Save M-Miyazako/47628722ac78f4b16c7fb0d96f00daa5 to your computer and use it in GitHub Desktop.
Save M-Miyazako/47628722ac78f4b16c7fb0d96f00daa5 to your computer and use it in GitHub Desktop.
# Storyboardからインスタンスを生成する
import UIKit
/// Storyboardからインスタンスを生成可能なプロトコル
protocol Instantiatable: class {
/// Storyboardからインスタンスを生成する
static func instantiateFromStoryboard() -> Self
}
extension Instantiatable where Self: UIViewController {
/// instantiateFromStoryboardのデフォルト実装
static func instantiateFromStoryboard() -> Self {
let className = String(describing: type(of: self)).replacingOccurrences(of: ".Type", with: "")
let storyboardName = className.replacingOccurrences(of: "ViewController", with: "")
let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle(for: Self.self))
guard let vc = storyboard.instantiateViewController(withIdentifier: className) as? Self else {
fatalError("Could not instantiate \(className)")
}
return vc
}
}
extension Instantiatable where Self: UITableViewController {
/// instantiateFromStoryboardのデフォルト実装
static func instantiateFromStoryboard() -> Self {
let className = String(describing: type(of: self)).replacingOccurrences(of: ".Type", with: "")
let storyboardName = className.replacingOccurrences(of: "TableViewController", with: "")
let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle(for: Self.self))
guard let vc = storyboard.instantiateViewController(withIdentifier: className) as? Self else {
fatalError("Could not instantiate \(className)")
}
return vc
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment