从xib文件加载ViewController

我有一个MyViewController.swift和一个呈现MyViewController布局的MyViewController.xib。

我尝试了不同的方法加载这个视图控制器,包括:

 //1 let myVC = UINib(nibName: "MyViewController", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? MyViewController //2 let myVC = NSBundle.mainBundle().loadNibNamed("MyViewController", owner: self, options: nil)[0] as? MyViewController //3 let myVC = MyViewController(nibName: "MyViewController", bundle: nil) 

第三个是唯一成功的初始化,但前两个导致错误:

由于未捕获的exception’NSUnknownKeyException’而终止应用,

reason:'[setValue:forUndefinedKey:]:此类不是密钥XXX的密钥值编码兼容。

这些加载方法有什么问题?

斯威夫特3

 let myViewController = MyViewController(nibName: "MyViewController", bundle: nil) self.present(myViewController, animated: true, completion: nil) 

或推入导航控制器

 self.navigationController!.pushViewController(MyViewController(nibName: "MyViewController", bundle: nil), animated: true) 

文件的所有者

注意File's Owner 。 在您的情况下, File's OwnerMyViewController

以下代码,如果它在类Foo执行。

 // If `self` is an instance of `Foo` class. // In this case, `File's Owner` will be a `Foo` instance. let myVC = NSBundle.mainBundle().loadNibNamed("MyViewController", owner: self, options: nil)[0] as? MyViewController 

它通过self作为owner 。 因此, File's OwnerFoo ,而不是MyViewController 。 然后,对于Foo类,那些IBOutlet无法连接到Foo ,它用于MyViewController 。 所以,它崩溃了。

问题不在于方法…你可能保留了一个sockets(XXX)连接了一些uielement并将其从相应的控制器中删除…我在下面添加示例… 在此处输入图像描述

上面的按钮现在连接到控制器,但当我评论sockets 在此处输入图像描述

我的应用程序崩溃了 在此处输入图像描述

在此处输入图像描述

所以尝试找到viewcontroller中缺少的sockets(xxx)但是在xib文件中。希望它有帮助:)

我有同样的问题。 自动生成的xib中有一个UIView。 您必须删除视图,将新视图控制器添加到xib,将视图控制器类设置为所需的视图控制器类,然后连接sockets。 完成所有这些后,您可以使用上面提供的代码来获取此视图控制器的实例,如下所示:

 if let menuVC = Bundle.main.loadNibNamed("MenuViewController", owner: nil, options: nil)?.first as? MenuViewController { menuVC.profileType = profileType vc.present(menuVC, animated: true, completion: nil) } 

试试下面的代码,

// 1

 let nib = UINib(nibName: "MyViewController", bundle:nil) myVC = nib.instantiateWithOwner(self, options: nil)[0] as? MyViewController 

要么

 myVC = nib.instantiateWithOwner(self, options: nil).first as? MyViewController 

// 2

 let nib : NSArray = NSBundle.mainBundle().loadNibNamed("MyViewController", owner: self, options: nil) myVC = nib.objectAtIndex(0) as? MyViewController 

这会奏效。