如何将xib文件设置为initialViewController?

时间:2016-05-13 10:20:56

标签: ios objective-c xcode swift swift2

由于我甚至无法完成与故事板的一次成功合并,我试图切换到xib文件。我试图将一个xib文件设置为initialViewController,就像在storyboard中一样,所以首先我在故事板中禁用了该属性。根据谷歌的一些例子,我做了一个应该返回xib文件的扩展程序:

extension UIViewController {
    class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIViewController? {
        return UINib(
            nibName: nibNamed,
            bundle: bundle
            ).instantiateWithOwner(nil, options: nil)[0] as? UIViewController
    }

然后从app委托调用该类函数,并尝试像这样以root视图控制器加载xib文件:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.


        let mainView = UIViewController.loadFromNibNamed("MainView")
        //window?.addSubview(mainView!)
        self.window?.rootViewController = mainView

        return true
    }

我的xib文件名是MainView.xib,我有一个UIView和一个MainViewController,MainViewController继承自ViewController,它仍然是空的:

enter image description here

enter image description here

enter image description here

无论我尝试什么,我都会得到相同的错误信息:

Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?

1 个答案:

答案 0 :(得分:3)

您仍然将项目设置为使用Main.storyboard文件。在项目/常规选项卡中,您需要清除此部分:

enter image description here

如果您这样做,您还需要自己创建UIWindow并设置应用委托的window属性,因为如果您不使用故事板,则不会创建该属性。有关详细信息,请参阅How to create an Empty Application in Xcode 6 without Storyboard