【问题标题】:Stop a executing a function when if statement returns true当 if 语句返回 true 时停止执行函数
【发布时间】:2020-12-13 00:01:11
【问题描述】:

我有一个允许用户保存个人资料的应用。为了让他们能够注册,我想检查一下他们是否同意应用程序的条款和条件。我遇到的问题是,如果用户不同意他们,他们会看到一个 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 的执行,只有在没有选中这些框的情况下。

【问题讨论】:

  • 在警报函数中使用带有闭包的完成块。

标签: ios swift function execution


【解决方案1】:

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

    checkIfChecked()
    

这必须在 checkIfChecked 之后,这样才可以显示 alertControllers。

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

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

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 2021-01-15
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2022-01-24
    相关资源
    最近更新 更多