【问题标题】:How to check conditions before performing navigation segue如何在执行导航 segue 之前检查条件
【发布时间】:2021-04-21 12:11:45
【问题描述】:

我有一个故事板控制的应用程序。在注册页面上,我想在按下注册按钮时将用户发送到主页。所以我将一个segue从按钮拖到主页。但是在执行 segue 之前我无法检查条件。但是如果我创建一个 segue 并以编程方式执行它,主页会出现在注册页面上,允许用户向后滑动。有人可以告诉我如何在执行 segue 之前检查条件,或者如果以编程方式执行,则不允许用户返回注册页面。这是我的故事板。 Main.storyboard

【问题讨论】:

    标签: ios swift storyboard


    【解决方案1】:

    Xcode 12.0 Swift 5.0

    • 首先,您需要将“注册”按钮连接到代码中的 IBAction;
    • 在 IBAction 中可以调用函数: func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil)
    • 如果条件一切都成功,则调用此函数,否则 return 会出错。

    退出按钮示例:

    private func showLoginViewController() {
        // Creates the view controller with the specified identifier
        let vc = storyboard?.instantiateViewController(withIdentifier: "loginForm") as! LoginViewController
        let navigationVC = UINavigationController(rootViewController: vc)
        navigationVC.modalPresentationStyle = .fullScreen
        present(navigationVC, animated: true, completion: nil)
    }
    
    // Tap on button
    @IBAction func signOutUserButton(_: UIButton) {
        let alertController = UIAlertController(title: nil, message: "Are you sure you want to sign out?", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Sign Out", style: .destructive, handler: { _ in
    
            // Condition where I check possibility to sign out
            self.signOut()
    
        }))
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alertController, animated: true)
    }
    
    private func signOut() {
        let firebaseAuth = Auth.auth()
        do {
            try firebaseAuth.signOut()
    
            // If everything is okay then perform segue
            showLoginViewController()
    
        } catch let signOutError as NSError {
    
            // Otherwise show error
            print("Error signing out: %@", signOutError)
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 我应该在 shouldPerformSegue() 函数中调用什么,因为它需要返回一个 Bool
      • 正如你所写的检查条件。请点击链接并阅读文档。
      • 我尝试了条件只是为了测试,即使 shouldPerformSegue 返回 false,仍然在按钮单击时执行 segue
      • 你重新连接segue了吗? shouldPerformSegue 仅在代码中调用 performSegue 后有效
      • 是的。我将 segue 从视图控制器连接到目标控制器
      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 2013-03-28
      • 1970-01-01
      • 2021-03-09
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多