ios 在 appdelegate 中设置初始视图控制器 - swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26753925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:30:57  来源:igfitidea点击:

set initial viewcontroller in appdelegate - swift

ios

提问by Abubakar Moallim

I would like to set the initial viewcontroller from the appdelegate. I found a really good answer, however it's in Objective C and im having trouble achieving the same thing in swift.

我想从 appdelegate 设置初始视图控制器。我找到了一个非常好的答案,但是它在目标 C 中,我无法快速实现相同的目标。

Programmatically set the initial view controller using Storyboards

使用 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;
}

Anyone able to help?

任何人都可以提供帮助?

I want the initial Viewcontroller to be dependent on certain conditions being met using a conditional statement.

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

回答by Abubakar Moallim

I used this thread to help me convert the objective C to swift, and its working perfectly.

我使用这个线程来帮助我将目标 C 转换为 swift,并且它工作得很好。

Instantiate and Present a viewController in Swift

在 Swift 中实例化并呈现一个 viewController

Swift 2code:

斯威夫特 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 3code:

斯威夫特 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
}

回答by protikhonoff

Try this. For example: You should use UINavigationControlleras initial view controller. Then, you can set any view controller as root from storyboard.

尝试这个。例如:您应该UINavigationController用作初始视图控制器。然后,您可以将任何视图控制器设置为故事板的根。

 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
}

See my storyboard screen.

查看我的故事板屏幕。

回答by Eridana

For Swift 3, Swift 4:

对于 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
    }

If you want to use UINavigationControlleras root:

如果您想以UINavigationControllerroot身份使用:

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:

从 xib 实例化根视图控制器:

It is almost the same, but instead of lines

它几乎相同,但不是线条

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

you'll have to write

你必须写

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

回答by Jibin Jose

if you are not using storyboard, you can try this

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

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
}

回答by John Bushnell

Here is a good way to approach it. This example places a navigation controller as the root view controller, and puts the view controller of your choice within it at the bottom of the navigation stack, ready for you to push whatever you need to from it.

这是处理它的好方法。这个例子将一个导航控制器作为根视图控制器,并将您选择的视图控制器放在导航堆栈的底部,准备好从它推送您需要的任何内容。

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()
}

To make this example work you would set "MainViewController" as the Storyboard ID on your main view controller, and the storyboard's file name in this case would be "MainStoryboard.storyboard". I rename my storyboards this way because Main.storyboard to me is not a proper name, particularly if you ever go to subclass it.

为了使这个示例工作,您需要将“MainViewController”设置为主视图控制器上的故事板 ID,在这种情况下,故事板的文件名将是“MainStoryboard.storyboard”。我以这种方式重命名我的故事板,因为 Main.storyboard 对我来说不是一个合适的名字,特别是如果你去继承它。

回答by gamal

For new Xcode 11.xxx and Swift 5.xx, where the target it set to iOS 13+.

对于新的 Xcode 11.xxx 和 Swift 5.xx,目标设置为 iOS 13+。

For the new project structure, AppDelegate does not have to do anything regarding rootViewController.

对于新的项目结构,AppDelegate 不需要对 rootViewController 做任何事情。

A new class is there to handle window(UIWindowScene) class -> 'SceneDelegate' file.

有一个新类来处理 window(UIWindowScene) 类 -> 'SceneDelegate' 文件。

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = // Your RootViewController in here
        self.window = window
        window.makeKeyAndVisible()
    }

}

回答by Patel Jigar

i had done it on objective-c hope it will be usefull for u

我已经在objective-c上做了,希望它对你有用

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];

回答by Kunal

I had done in Xcode 8 and swift 3.0 hope it will be useful for u, and its working perfectly. Use following code :

我已经在 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
}

And If you are using the navigation controller, then use following code for that:

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

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
}

回答by Jamil Hasnine Tamim

Code for Swift 4.2 and 5 code:

Swift 4.2 和 5 代码的代码:

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: "dashboardVC")

     self.window?.rootViewController = initialViewController
     self.window?.makeKeyAndVisible()
}

And for Xcode 11+and for Swift 5+:

而对于Xcode 11+and for Swift 5+

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

     var window: UIWindow?

     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
         if let windowScene = scene as? UIWindowScene {
             let window = UIWindow(windowScene: windowScene)

              window.rootViewController = // Your RootViewController in here

              self.window = window
              window.makeKeyAndVisible()
         }
    }
}

回答by Wade Sellers

Swift 4:

斯威夫特 4:

Add these lines inside AppDelegate.swift, within the didFinishLaunchingWithOptions() function...

在 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
}

Now, for example, many times we do something like this when we want to either drive the user to a login screen or to a initial setup screenl or back to the mainScreen of the app, etc. If you want to do something like that too, you can use this point as a fork-in-the-road for that.

现在,例如,当我们想要将用户驱动到登录屏幕或初始设置屏幕或返回应用程序的主屏幕等时,很多时候我们会做这样的事情。如果你也想做类似的事情,你可以使用这个点作为一个岔路口。

Think about it. You could have a value stored in NSUserDefaults for instance that held a userLoggedIn Boolean and if userLoggedIn == false { use this storyboard & initialViewController... } else { use this storyboard & initialViewController... }

想想看。例如,您可以将一个值存储在 NSUserDefaults 中,该值包含一个 userLoggedIn 布尔值和if userLoggedIn == false { use this storyboard & initialViewController... } else { use this storyboard & initialViewController... }