Last active
April 15, 2019 11:17
-
-
Save serhii-londar/de3d1eb26d6bb098c0c564b43a0bfee5 to your computer and use it in GitHub Desktop.
Pure protocol factory for Interface Builder-based views(https://blog.hal.codes/ib-constructible)
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
protocol IBConstructible: AnyObject { | |
static var nibName: String { get } | |
static var bundle: Bundle { get } | |
} | |
extension IBConstructible { | |
static var nibName: String { | |
return String(describing: Self.self) | |
} | |
static var bundle: Bundle { | |
return Bundle(for: Self.self) | |
} | |
} | |
extension IBConstructible where Self: UIViewController { | |
static var fromNib: Self { | |
let storyboard = UIStoryboard(name: nibName, bundle: bundle) | |
guard let viewController = storyboard.instantiateInitialViewController() as? Self else { | |
fatalError("Missing view controller in \(nibName).storyboard") | |
} | |
return viewController | |
} | |
} | |
extension IBConstructible where Self: UIView { | |
static var fromNib: Self { | |
let xib = UINib(nibName: nibName, bundle: bundle) | |
guard let view = xib.instantiate(withOwner: nil, options: nil).first as? Self else { | |
fatalError("Missing view in \(nibName).xib") | |
} | |
return view | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment