I am trying to make an extension of UIViewController
nib
registration.
So instead of PastOrdersViewController(nibName: "PastOrdersViewController", bundle: nil)
we can do something like
extension UIViewController {
func loadNib(vc: UIViewController,nibName: String) -> UIViewController{
return vc(nibName: nibName, bundle: nil)//Error: Cannot call value of non-function type 'UIViewController'
}
}
However, I get the following error:-
Error:Cannot call value of non-function type 'UIViewController'
The error occurs from the fact that the vc
parameter points to an instance of UIViewController
, and from how the method looks like you want to instead call the initializer on the controller class.
You could use Self
, and drop the first argument, this will make the loadFromNib
method really simple. Another optimization that you could make would be to declare the nib name as optional, and give it a default value of nil
:
extension UIViewController {
static func loadFromNib(_ nibName: String? = nil) -> Self {
return self.init(nibName: nibName, bundle: nil)
}
}
You'd then be able to nicely use the method like this:
let vc = MyViewController.loadFromNib() // loads from MyViewController.nib
, or
let vc = MyViewController.loadFromNib("Custom") // loads from Custom.nib