Load and Present a second viewcontroller at launch

时间:2018-01-25 16:20:03

标签: ios swift uiviewcontroller swift4

I am trying to present a second viewcontroller on top of the first at startup without dismissing the first. This post Swift 3 - loading multiple ViewControllers at launch certainly looks like it has the answer. It recommends:

Add in your main view controller

var secondViewController:UIViewController!

And in your viewDidLoad:

secondViewController: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourIdentifier") as! SecondViewController

That's it. When you want to present it, use:

self.present(secondViewController, animated: true, completion: nil)  

This third line works great if, for example, I attach it as an action to a button. However, it does not work if it is in viewDidLoad: of the first viewController. This is what I need.

How can I automatically present the second viewController on top of the first viewController at launch?

4 个答案:

答案 0 :(得分:3)

您需要在视图控制器中的适当位置执行此操作。当您的视图控制器出现时,有几种方法被调用,它们用于不同的任务。

要呈现另一个视图控制器,您应该将其放在viewWillAppear:viewDidAppear:中,因为viewDidLoad:在演示文稿中还为时过早。

在此处阅读有关这些方法的更多信息:

https://stackoverflow.com/a/5659007/4543629

答案 1 :(得分:1)

我认为这取决于你想要做什么。如果您想在启动时推送ViewController,您也可以尝试在func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

中的AppDelegate中显示它

类似的东西:(就像我说这取决于你的用例)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let secondViewController = storyboard.instantiateViewController(withIdentifier: "yourIdentifier") as! SecondViewController
    let navigationController = UINavigationController(rootViewController: SecondViewController)
    self.window?.makeKeyAndVisible()
    self.window?.rootViewController?.present(navigationController, animated: false, completion: {() -> Void in
        mainMenuVC.tabBarControl = tabBarController
        })
    return true
}

答案 2 :(得分:0)

您可以访问AppDelegate和设置窗口,或者如果您使用storyboard将箭头拖动到ViewControler您想要的内容

答案 3 :(得分:0)

是的,LGP的第一个评论可以解决问题。谢谢。我在这里作为答案提出。我将此函数添加到第一个viewController:

override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(true)
   self.present(secondViewController, animated: true, completion: nil)  
}

如果有人想发表评论,我在调用super.viewDidAppear(true)时没有考虑其是否合适。