【问题标题】:Call a function from AppDelegate and use that function to perform segue从 AppDelegate 调用一个函数并使用该函数执行 segue
【发布时间】:2019-07-31 20:47:02
【问题描述】:

我正在尝试从 AppDelegate 调用一个函数,并尝试使用该函数执行 segue。


(点击图片放大)

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)
}

这些是超出执行范围的错误。

【问题讨论】:

  • 请告诉我我需要在此代码中进行哪些更改才能成功执行?
  • 您的项目中有几个视图控制器,其中一个是您发布的代码,因为如果您尝试从 LoginVC 以外的另一个视图控制器执行它,它将找不到 segue,即您收到的错误消息。
  • 你在 loginVC 上的prepareForSegue 上做特别的事情吗?
  • @EduristicIndian 如果您@您回复的人,他们将在收件箱中收到消息。快速提示!
  • @UpholderOfTruth 我正在尝试从 LoginVC 本身执行 segue

标签: ios swift uiviewcontroller appdelegate


【解决方案1】:

如果您在 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
}

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

【讨论】:

    【解决方案2】:

    这里基于 cmets 是一种简单的方法,可以将对现有登录视图控制器的引用放入应用委托中,以便您可以对其执行 segue。

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

    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") }
    }
    

    现在这可能不是最好的方法,但在不了解项目更多信息的情况下,它是一种让它工作的简单方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多