Skip to content

Instantly share code, notes, and snippets.

@ryotapoi
Created May 25, 2017 10:46
Show Gist options
  • Save ryotapoi/968a49aaba7fd97499b9121ed6aaa724 to your computer and use it in GitHub Desktop.
Save ryotapoi/968a49aaba7fd97499b9121ed6aaa724 to your computer and use it in GitHub Desktop.
StoryboardからUIViewControllerを生成する。 UIViewControllerひとつに複数のStoryboardがある場合を想定。
public struct Storyboard {
public init(_ name: String, bundle: Bundle? = nil) {
self.name = name
self.bundle = bundle
}
public var name: String
public var bundle: Bundle?
public func instantiate<VCType>(_ vcType: VCType.Type = VCType.self, identifier: String? = nil) -> VCType? {
if let identifier = identifier {
return UIStoryboard(name: name, bundle: bundle).instantiateViewController(withIdentifier: identifier) as? VCType
} else {
return UIStoryboard(name: name, bundle: bundle).instantiateInitialViewController() as? VCType
}
}
}
public struct StoryboardLoader<VCType: UIViewController> {
let storyboard: Storyboard
let identifier: String?
public init(_ storyboard: Storyboard, identifier: String? = nil) {
self.storyboard = storyboard
self.identifier = identifier
}
// Storyboard構造体の定義を横着するとき用
public init(storyboardName: String, identifier: String? = nil, bundle: Bundle? = nil) {
self.storyboard = Storyboard(storyboardName, bundle: bundle ?? Bundle(for: VCType.self))
self.identifier = identifier
}
public func instantiate() -> VCType {
return storyboard.instantiate(VCType.self, identifier: identifier)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment