无法在Swift的Storyboard中加载UIViewController XIB文件 [英] Can't Load UIViewController XIB file in Storyboard in Swift
问题描述
我已阅读使用XCode故事板来实例化使用XIB进行设计的视图控制器但是我在使用Swift(使用Xcode 6 Beta 6)时遇到了麻烦。我想知道我是否做错了或者这个功能不再可用了吗?
I've read Using XCode storyboard to instantiate view controller that uses XIB for its design but I'm having troubles making this work in Swift (Using Xcode 6 Beta 6). I'm wondering if I've done something wrong or if this functionality isn't available anymore?
我创建了一个简单的存储库, https://github.com/jer-k/StoryboardTesting-Swift ,展示了上述方法。
I created a simple repository, https://github.com/jer-k/StoryboardTesting-Swift, that showcases the above approach.
我设法通过添加和覆盖init来解决问题
I managed to solve the issue by adding and override to init
required init(coder aDecoder: NSCoder) {
super.init(nibName: "TestViewController", bundle: NSBundle.mainBundle())
}
但我想知道是否仍有可能让故事板为我处理这个问题。创建一个超类让我的所有UIViewControllers继承上面的代码并不是世界上最麻烦的事情,但我现在只是好奇。
but I'm wondering if it is still possible to have the storyboard handle this for me. Creating a superclass to have all my UIViewControllers inherit from with the above code isn't the most cumbersome thing in the world, but I'm just curious at this point.
推荐答案
如果视图控制器是Swift类,那么种子5破坏了视图控制器可以通过名称找到其xib的机制。原因是,Swift认为类的名称与您给它的名称(以及您给出的xib文件的名称)不同;该名称已被修改,特别是通过预先添加模块名称(即Swift类具有命名空间)。
What's happened is that Seed 5 broke the mechanism whereby a view controller can find its xib by name, if the view controller is a Swift class. The reason is that the name of the class, in Swift's mind, is not the same as the name you gave it (and the name you gave the xib file); the name has been "mangled", in particular by prepending the module name (i.e. Swift classes have namespacing).
我提供三种解决方法:
-
您的解决方法很好(明确地按名称加载.xib文件)
Your workaround is a good one (load the .xib file by name explicitly)
将.xib文件命名为 MyModule.TestViewController.xib ,其中 MyModule
是捆绑包的名称(即项目名称)(这是苹果建议的,但我讨厌它)
Name the .xib file MyModule.TestViewController.xib, where MyModule
is the name of your bundle (i.e. the name of the project) (this is what Apple advises, but I hate it)
使用 @objc(TestViewController)
之前查看控制器的类
声明,以克服名称错误,这是破坏机制(这是我赞成的方法)
Use @objc(TestViewController)
before the view controller's class
declaration to overcome the name mangling which is what's breaking the mechanism (this is the approach I favor)
请参阅我的讨论: https://stackoverflow.com/a/25163757/ 341994 和我的进一步讨论从那里开始: https://stackoverflow.com/a/25152545/34 1994
See my discussion here: https://stackoverflow.com/a/25163757/341994 and my further discussion linked to from there: https://stackoverflow.com/a/25152545/341994
编辑此错误在iOS 9 beta 4中得到修复。如果nib文件搜索失败,iOS 9现在剥离了模块名称关闭视图控制器类名称并再次执行nib文件搜索。
EDIT This bug is fixed in iOS 9 beta 4. If the nib file search fails, iOS 9 now strips the module name off the view controller class name and performs the nib file search a second time.
这篇关于无法在Swift的Storyboard中加载UIViewController XIB文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!