在Mac应用程序中添加自定义视图控制器作为根视图控制器?

时间:2017-08-31 07:13:13

标签: swift macos cocoa

我已经检查了这个问题的大多数答案,但主要是针对Cocoa Touch。我需要在我的appdelegate中为mac应用程序实现它。

一旦用户登录,他将被重定向到主屏幕,否则进入登录屏幕。

let controller:NSWindowController = NSWindowController()
let viewController:NSViewController

let storyboard = NSStoryboard.init(name: "Main", bundle: nil)
    let stringLoginStatus = NSUserDefaults.standardUserDefaults().objectForKey(Constants.Key_LoginStatus) as? String
    if stringLoginStatus != nil
    {
        if stringLoginStatus == "true"
        {
            viewController = storyboard.instantiateControllerWithIdentifier("Channel") as! NSViewController
        }
        else{
            viewController = storyboard.instantiateControllerWithIdentifier("ViewController") as! NSViewController
        }
    }
    else{
        viewController = storyboard.instantiateControllerWithIdentifier("ViewController") as! NSViewController
    }

    controller.window?.contentViewController = viewController
    controller.window?.makeKeyAndOrderFront(self)

控制器未初始化时显示错误。

1 个答案:

答案 0 :(得分:1)

尝试使用此代码更改视图控制器: -

UIApplication.appWindow.rootViewController = UIStoryboard.main.instantiateViewController(withIdentifier: "customViewControl")

// MARK:制作UIApplication扩展以获取appWindow

    extension UIApplication {
        class var appWindow: UIWindow! {
            return (UIApplication.shared.delegate?.window!)!
        }
    }

// MARK:制作Storyboard扩展程序以获取主屏幕

extension UIStoryboard {
    class var main: UIStoryboard {
        let storyboardName: String = Bundle.main.object(forInfoDictionaryKey: "UIMainStoryboardFile") as! String
        return UIStoryboard(name: storyboardName, bundle: nil)
    }

}