在ViewDidLoad中执行Segue [复制]

问题描述 投票:4回答:3

这个问题在这里已有答案:

我试图在第一次加载应用程序时执行segue。我可以在调试器中看到我的打印消息,但Perform Segue不起作用。我没有得到任何错误。有人可以告诉我什么错了吗?

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.




    }
ios swift xcode segue viewdidload
3个回答
24
投票

您不能在viewDidLoad()中使用performSegue()。将其移至viewDidAppear()。

在viewDidLoad()时,当前视图甚至没有附加到窗口,因此不可能进行segue。


0
投票

您也可以使用不同的方法 - 根据rootViewControllerboolean将主窗口的isFirstLaunch更改为您选择的视图控制器

UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController


0
投票

我想你也可以将你的segue放入Dispatch.main.async

    DispatchQueue.main.async {
        if  isFirstLaunch == false {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testFalse") 
        } else {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testTrue")
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.