Created
February 6, 2020 07:39
-
-
Save M-Miyazako/47628722ac78f4b16c7fb0d96f00daa5 to your computer and use it in GitHub Desktop.
# Storyboardからインスタンスを生成する
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 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