Loading ViewController from xib file
Swift 3
let myViewController = MyViewController(nibName: "MyViewController", bundle: nil)self.present(myViewController, animated: true, completion: nil)
or push in navigation controller
self.navigationController!.pushViewController(MyViewController(nibName: "MyViewController", bundle: nil), animated: true)
extension UIViewController { static func loadFromNib() -> Self { func instantiateFromNib<T: UIViewController>() -> T { return T.init(nibName: String(describing: T.self), bundle: nil) } return instantiateFromNib() }}
Use it as the following:-
let testVC = TestVC.loadFromNib()
Notice the File's Owner
. In your case, the File's Owner
must be MyViewController
, or its sub-class
.
And the following code, if it executes in class Foo
.
// If `self` is an instance of `Foo` class.// In this case, `File's Owner` will be a `Foo` instance due to the `self` parameter.let myVC = NSBundle.mainBundle().loadNibNamed("MyViewController", owner: self, options: nil)[0] as? MyViewController
It assigns self
as owner
. So, the File's Owner
is Foo
, not MyViewController
. Then, for Foo
class, those IBOutlet
cannot be connected to Foo
. So, it throws exception.