首页 文章

在appdelegate中设置初始viewcontroller - swift

提问于
浏览
109

我想从appdelegate设置初始viewcontroller . 我找到了一个非常好的答案,但它是在Objective C中,我很难在swift中实现同样的功能 .

Programmatically set the initial view controller using Storyboards

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

    UIViewController *viewController = // determine the initial view controller here and instantiate   it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];

    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    return YES;
}

有人能帮忙吗?

我希望初始Viewcontroller依赖于使用条件语句满足的某些条件 .

14 回答

  • 236

    我使用这个线程帮助我将目标C转换为swift,并且它的工作完美 .

    Instantiate and Present a viewController in Swift

    Swift 2 代码:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
    
        let initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginSignupVC")
    
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    
        return true
    }
    

    Swift 3 代码:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
    
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginSignupVC")
    
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    
        return true
    }
    
  • 1

    试试这个 . 例如:您应该使用 UINavigationController 作为初始视图控制器 . 然后,您可以从故事板中将任何视图控制器设置为root .

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as UINavigationController
        let rootViewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("VC") as UIViewController
        navigationController.viewControllers = [rootViewController]
        self.window?.rootViewController = navigationController
        return true
    }
    

    my storyboard screen.

  • 21

    如果你没有使用故事板,你可以试试这个

    var window: UIWindow?
    var initialViewController :UIViewController?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
        initialViewController  = MainViewController(nibName:"MainViewController",bundle:nil)
    
        let frame = UIScreen.mainScreen().bounds
        window = UIWindow(frame: frame)
    
        window!.rootViewController = initialViewController
        window!.makeKeyAndVisible()
    
        return true
    }
    
  • 6

    For Swift 3, Swift 4:

    Instantiate root view controller from storyboard:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // this line is important
            self.window = UIWindow(frame: UIScreen.main.bounds)
    
            // In project directory storyboard looks like Main.storyboard,
            // you should use only part before ".storyboard" as it's name,
            // so in this example name is "Main".
            let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    
            // controller identifier sets up in storyboard utilities
            // panel (on the right), it called Storyboard ID
            let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
    
            self.window?.rootViewController = viewController
            self.window?.makeKeyAndVisible()        
            return true
        }
    

    如果要以root身份使用 UINavigationController

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // this line is important
            self.window = UIWindow(frame: UIScreen.main.bounds)
    
            let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
            let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
            let navigationController = UINavigationController.init(rootViewController: viewController)
            self.window?.rootViewController = navigationController
    
            self.window?.makeKeyAndVisible()        
            return true
        }
    

    Instantiate root view controller from xib:

    它几乎相同,但不是线条

    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
    

    你必须写

    let viewController = YourViewController(nibName: "YourViewController", bundle: nil)
    
  • 38

    这是接近它的好方法 . 此示例将导航控制器作为根视图控制器放置,并将您选择的视图控制器放在导航堆栈的底部,准备好从中推送您需要的任何内容 .

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
    {
        // mainStoryboard
        let mainStoryboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
    
        // rootViewController
        let rootViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainViewController") as? UIViewController
    
        // navigationController
        let navigationController = UINavigationController(rootViewController: rootViewController!)
    
        navigationController.navigationBarHidden = true // or not, your choice.
    
        // self.window
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    
        self.window!.rootViewController = navigationController
    
        self.window!.makeKeyAndVisible()
    }
    

    要使此示例正常工作,您可以在主视图控制器上将“MainViewController”设置为Storyboard ID,在这种情况下,storyboard的文件名将为“MainStoryboard.storyboard” . 我以这种方式重命名我的故事板,因为Main.storyboard对我来说不是一个正确的名称,特别是如果你去它的子类 .

  • 2

    我是在目标上做到的 - 希望它对你有用

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    UIViewController *viewController;
    
    NSUserDefaults *loginUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *check=[loginUserDefaults objectForKey:@"Checklog"];
    
    if ([check isEqualToString:@"login"]) {
    
        viewController = [storyboard instantiateViewControllerWithIdentifier:@"SWRevealViewController"];
    } else {
    
        viewController = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    }
    
    
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
    
  • 0

    对于 swift 4.0 .

    didfinishedlaunchingWithOptions 方法的 AppDelegate.swift 文件中,输入以下代码 .

    var window: UIWindow?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
    
        let rootVC = MainViewController() // your custom viewController. You can instantiate using nib too. UIViewController(nib name, bundle)
        //let rootVC = UIViewController(nibName: "MainViewController", bundle: nil) //or MainViewController()
        let navController = UINavigationController(rootViewController: rootVC) // Integrate navigation controller programmatically if you want
    
        window?.rootViewController = navController
    
        return true
    }
    

    希望它能正常工作 .

  • 6

    我在Xcode 8和swift 3.0中做过希望它对你有用,并且它的工作完美 . 使用以下代码:

    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {       
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewController")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
        return true
    }
    

    如果您使用的是导航控制器,请使用以下代码:

    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController
        let initialViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController")
        navigationController.viewControllers = [initialViewController]
        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()      
        return true
    }
    
  • 5

    Swift 4:

    在appDelegate.swift中,在didFinishLaunchingWithOptions()函数中添加这些行...

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
        // Setting the Appropriate initialViewController
    
        // Set the window to the dimensions of the device
        self.window = UIWindow(frame: UIScreen.main.bounds)
    
        // Grab a reference to whichever storyboard you have the ViewController within
        let storyboard = UIStoryboard(name: "Name of Storyboard", bundle: nil)
    
        // Grab a reference to the ViewController you want to show 1st.
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "Name of ViewController")
    
        // Set that ViewController as the rootViewController
        self.window?.rootViewController = initialViewController
    
        // Sets our window up in front
        self.window?.makeKeyAndVisible()
    
        return true
    }
    

    现在,例如,当我们想要将用户驱动到登录屏幕或初始设置屏幕或返回到应用程序的主屏幕等时,我们多次执行类似这样的操作 . 如果您想要执行类似的操作,你可以把这一点用作叉路 .

    想一想 . 你可以在NSUserDefaults中存储一个值,例如持有userLoggedIn布尔值和 if userLoggedIn == false { use this storyboard & initialViewController... } else { use this storyboard & initialViewController... }

  • 18

    那么上面/下面的所有答案都会产生关于故事板中没有入口点的警告 .

    如果你想拥有2个(或更多)依赖于某些条件的入口视图控制器(比如conditionVariable),你应该做的是:

    • 在Main.storyboard中创建UINavigationController without rootViewController,将其设置为入口点

    • 创建2(或更多)"Show" segues进入视图控制器,为它们分配一些id,比如说id1和id2

    • 使用下一个代码:

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
       var window: UIWindow?
    
       func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
           let navigationController = window!.rootViewController! as! UINavigationController
           navigationController.performSegueWithIdentifier(conditionVariable ? "id1" : "id2")
    
           return true
       }
    

    希望这可以帮助 .

  • 1

    Just in case you want to do it in the view controller and not in the app delegate: 只需在视图控制器中获取对AppDelegate的引用并重置它's window object with the right view controller as it' s rootviewController .

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let yourVC = mainStoryboard.instantiateViewControllerWithIdentifier("YOUR_VC_IDENTIFIER") as! YourViewController
    appDelegate.window?.rootViewController = yourVC
    appDelegate.window?.makeKeyAndVisible()
    
  • 11
    I worked out a solution on Xcode 6.4 in swift. 
    
    // I saved the credentials on a click event to phone memory
    
        @IBAction func gotobidderpage(sender: AnyObject) {
     if (usernamestring == "bidder" && passwordstring == "day303")
            {
                rolltype = "1"
    
    NSUserDefaults.standardUserDefaults().setObject(usernamestring, forKey: "username")
    NSUserDefaults.standardUserDefaults().setObject(passwordstring, forKey: "password")
    NSUserDefaults.standardUserDefaults().setObject(rolltype, forKey: "roll")
    
    
                self.performSegueWithIdentifier("seguetobidderpage", sender: self)
    }
    
    
    // Retained saved credentials in app delegate.swift and performed navigation after condition check
    
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
    let usernamestring = NSUserDefaults.standardUserDefaults().stringForKey("username")
    let passwordstring = NSUserDefaults.standardUserDefaults().stringForKey("password")
    let rolltypestring = NSUserDefaults.standardUserDefaults().stringForKey("roll")
    
            if (usernamestring == "bidder" && passwordstring == "day303" && rolltypestring == "1")
            {
    
                // Access the storyboard and fetch an instance of the view controller
                var storyboard = UIStoryboard(name: "Main", bundle: nil)
                var viewController: BidderPage = storyboard.instantiateViewControllerWithIdentifier("bidderpageID") as! BidderPage
    
                // Then push that view controller onto the navigation stack
                var rootViewController = self.window!.rootViewController as! UINavigationController
                rootViewController.pushViewController(viewController, animated: true)
            }
    
            // Override point for customization after application launch.
            return true
        }
    
    
    
    Hope it helps !
    
  • 1

    这里是Swift 4中的完整解决方案,在didFinishLaunchingWithOptions中实现它

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
     let isLogin = UserDefaults.standard.bool(forKey: "Islogin")
        if isLogin{
            self.NextViewController(storybordid: "OtherViewController")
    
    
        }else{
            self.NextViewController(storybordid: "LoginViewController")
    
        }
    }
    

    在Appdelegate.swift中的任何位置写这个函数

    func NextViewController(storybordid:String)
    {
    
        let storyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let exampleVC = storyBoard.instantiateViewController(withIdentifier:storybordid )
       // self.present(exampleVC, animated: true)
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = exampleVC
        self.window?.makeKeyAndVisible()
    }
    
  • 14
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController
    
        self.window?.rootViewController = exampleViewController
    
        self.window?.makeKeyAndVisible()
    
        return true
    }
    

相关问题