Skip to content

Instantly share code, notes, and snippets.

@swift2931
Last active January 26, 2019 10:47
Show Gist options
  • Save swift2931/74cabc40cb9bda655f1db745851924d8 to your computer and use it in GitHub Desktop.
Save swift2931/74cabc40cb9bda655f1db745851924d8 to your computer and use it in GitHub Desktop.
Initialize a view controller with its view defined in storyboard
iOS development builds around storyboard.
my opinionated approach is to keep only 1 view controller in each storyboard.
use it only as the view of controller, but do most of the control in code.
you may wonder why not just using XIB?
first it requires you overriding loadView(), which is some overhead
second prototype cell is supported only in storyboard
it's just a lot easier to put it altogether
also you may use storyboard reference to do embeded view controller, which is
somewhat tedious to do in code
// example
// let vc = sb() as MainVC
extension UIViewController {
static var name: String {
return String(describing: self)
}
}
infix operator !?
public func !? <T>(wrapped: T?, nilDefault: @autoclosure () -> (value: T, text: String)) -> T {
assert(wrapped != nil, nilDefault().text)
return wrapped ?? nilDefault().value
}
func sb<T>() -> T where T: UIViewController {
return UIStoryboard(name: T.name, bundle: Bundle.main).instantiateInitialViewController() as? T !? (T(), "\(T.name) not instantiated")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment