首页 > 解决方案 > 当 if 语句返回 true 时停止执行函数

问题描述

我有一个允许用户保存他们的个人资料的应用程序。为了让他们能够注册,我想检查他们是否同意应用程序的条款和条件。我遇到的问题是,如果用户不同意他们,他们会看到一个 alertController 告诉他们同意。但是,该应用程序仍会继续执行其余代码。

    func checkIfChecked() {
            
    if self.checkbox.imageView.isHidden == true {
        let alert = UIAlertController(title: "Hold up!",message:" You must agree to our Community Guidelines before you can sign up.", preferredStyle: UIAlertController.Style.alert)
        let continueButton = UIAlertAction(title: "Got it!", style: .default, handler: {(_ action: UIAlertAction) -> Void in
        
           })
 
        continueButton.setValue(GREEN_Theme, forKey: "titleTextColor")
        alert.addAction(continueButton)
        self.present(alert, animated: true, completion: nil)
    }
    
    if self.checkbox2.imageView.isHidden == true {
        let alert = UIAlertController(title: "Hold up!",message:" You must agree to our Terms & Conditions before you can sign up.", preferredStyle: UIAlertController.Style.alert)
        let continueButton = UIAlertAction(title: "Got it!", style: .default, handler: {(_ action: UIAlertAction) -> Void in
        
           })
 
        continueButton.setValue(GREEN_Theme, forKey: "titleTextColor")
        alert.addAction(continueButton)
        self.present(alert, animated: true, completion: nil)
        
    }
    
}

   @objc func handleRegister() {
    
    checkIfChecked()

    let hud = JGProgressHUD(style: .dark)
    hud.textLabel.text = "Registering!"
    hud.show(in: view)
    guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text, let phonenumber = phonenumberTextField.text else {
        print("Error")
        return

其余代码.... }

}

如果选中复选框,则没有问题。但是如果他们没有被选中,那么用户信息仍然会在没有他们登录的情况下保存到数据库中。所以我试图在 checkIfChecked 被调用后停止 handleRegister 的执行,只有在没有选中这些框的情况下。

标签: iosswiftfunctionexecution

解决方案


不确定这是否是解决我遇到的问题的最安全方法,但我解决问题的方法是在 handleRegister 内部,我补充说

    checkIfChecked()
    

这必须在 checkIfChecked 之后才能显示警报控制器。

    if self.checkbox.imageView.isHidden == true {
        return
    } else  if self.checkbox2.imageView.isHidden == true {
        return
    }

如果这些行是真的,它会停止代码的执行。


推荐阅读