Perform Segue in ViewDidLoad [duplicate]

2019-02-18 06:01发布

This question already has an answer here:

I`m trying to perform a segue if its the first time the app is loading. I can see my print message in the debugger, but the Perform Segue is not working. I don't get any errors. Can somebody please tell me whats wrong?

import UIKit
import LocalAuthentication
let isFirstLaunch = UserDefaults.isFirstLaunch()
extension UserDefaults {
    // check for is first launch - only true on first invocation after app install, false on all further invocations
    // Note: Store this value in AppDelegate if you have multiple places where you are checking for this flag
    static func isFirstLaunch() -> Bool {
        let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
        let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
        if (isFirstLaunch) {

            UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
            UserDefaults.standard.synchronize()
        }
        return isFirstLaunch
    }
}

class loginVC: UIViewController {





    override func viewDidLoad() {

        super.viewDidLoad()

        if  isFirstLaunch == false {
          performSegue(withIdentifier: "setPassword", sender: self)
            print("testFalse") }
            else {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testTrue")}


        //       Do any additional setup after loading the view, typically from a nib.




    }

3条回答
Emotional °昔
2楼-- · 2019-02-18 06:31

I think you can also put your segue into a Dispatch.main.async

    DispatchQueue.main.async {
        if  isFirstLaunch == false {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testFalse") 
        } else {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testTrue")
        }
    }
查看更多
\"骚年 ilove
3楼-- · 2019-02-18 06:35

You can't use performSegue() from within viewDidLoad(). Move it to viewDidAppear().

At viewDidLoad() time, the current view isn't even attached to the window yet, so it's not possible to segue yet.

查看更多
男人必须洒脱
4楼-- · 2019-02-18 06:39

You can also use a different approach - change the main window's rootViewController to the view controller of your choice depending on isFirstLaunchboolean

UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController

查看更多
登录 后发表回答