从AppDelegate调用一个函数并使用该函数执行segue

时间:2019-03-10 10:12:17

标签: ios swift uiviewcontroller appdelegate

我试图从AppDelegate调用一个函数,然后使用该函数尝试执行segue。

My Storyboard
(点击图片放大)

func doSegue (_ verification : Bool) {
    if verification {
        print ("Segue performed")
        LoginVC ()
        .performSegue (withIdentifier: "tosignup", sender: nil)
    }
    else { print("An error occured while login") }
}
func btnremove () {
    print ("Segue performed 1")
    loginbtn.isHidden = true doSegue (true)
}

这些是无法执行的错误。

These are the errors which came beyond execution.

2 个答案:

答案 0 :(得分:0)

如果您在LoginVC中的prepareForSegue中没有做任何特别的事情,则可以在AppDelegate中启动根视图控制器:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if (verification) {
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoginVC")

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    } else {
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "SignupformVC")

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

    return true
}

还应该为视图控制器设置标识符。

答案 1 :(得分:0)

基于此处的注释的权利是一种简单的方法,可以将对现有登录视图控制器的引用放入应用程序委托中,以便您可以对其执行序列检查。

首先在应用程序委托中,您需要添加一个属性,用于对登录视图控制器的引用,如下所示:

public var loginVC: LoginVC?

现在,您可以在登录视图控制器中的viewDidLoad中设置此属性,如下所示:

    // Get the app delegate ensuring it is the right type.
    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
        appDelegate.loginVC = self
    }

然后回到应用程序委托中,您可以在doSegue方法中使用该属性,如下所示:

func doSegue (_ verification : Bool) {
    // Ensure that the loginVC property has been set and if not we can't perform the segue.
    guard let loginVC = self.loginVC else {
        print ("The login view controller is not presented")

        return
    }

    if verification {
        print ("Segue performed")
        // Use the property to perform the segue.
        loginVC.performSegue(withIdentifier: "tosignup", sender: nil)
    }
    else { print("An error occured while login") }
}

现在这可能不是最好的方法,但是如果不了解更多有关项目的信息,这是使它正常工作的简单方法。