简体   繁体   中英

How to set the Initial viewController in AppDelegate Programatically?

I know that this question was asked a couple of times but I tried all the solutions and nothing really worked for me.

I am currently working on an iOS Project and encountered a problem.

I am building an App which needs some personal information at the first launch. Therefore I use a NavigationController which I set to be the Initial View Controller in Storyboard.

Now I would like to check in my AppDelegate whether the User already entered the Personal Data. In this case I created a User Defaults KV Pair called "onboarding" of type Bool

If the Value is true , I would like to change the Initial View Controller to the main TabBarController , the rest of the App uses.

I hope this image can illustrate what I meant above: 在此处输入图片说明

I hope you can think of a way to solve this problem.

Thanks a lot for your help in advance. Have a great day!

1) Open your AppDelegate.swift and add property

var window: UIWindow?

2) In

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool

a) initialize this window:

window = UIWindow(frame: UIScreen.main.bounds)

b) set UIViewController you needed to window 's rootViewController property:

window?.rootViewController = myViewController

c) make this window key and visible:

window?.makeKeyAndVisible()

That is all. And don't forget to remove your storyboard from target settings: Remove storyboard from target

Hope its help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM