Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

ios - Can't Load UIViewController XIB file in Storyboard in Swift

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?

I created a simple repository, https://github.com/jer-k/StoryboardTesting-Swift, that showcases the above approach.

I managed to solve the issue by adding and override to init

required init(coder aDecoder: NSCoder) {
    super.init(nibName: "TestViewController", bundle: NSBundle.mainBundle())
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

I offer three workarounds:

  • Your workaround is a good one (load the .xib file by name explicitly)

  • 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)

  • 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)

See my discussion here: https://stackoverflow.com/a/25163757/341994 and my further discussion linked to from there: https://stackoverflow.com/a/25152545/341994

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...