You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift注册页面:条件判断生效时Segue仍跳转的问题排查

为什么错误时用户仍能跳转?问题出在segue的绑定方式!

你遇到的核心问题是segue的触发逻辑冲突:如果你的注册按钮是直接拖线到下一个视图控制器创建的Show segue,那么点击按钮时,系统会自动触发这个segue完成跳转,完全无视你代码里的条件判断——哪怕注册失败,跳转依然会发生。

看你的代码,其实你已经写了只有注册成功时才调用performSegue,但如果按钮本身绑定了segue,这个手动调用反而可能是多余的,甚至会导致重复跳转(不过你现在的情况是错误时也跳转,说明按钮直接关联了segue)。

解决方法

1. 移除按钮直接绑定的segue

打开Storyboard,找到那个从注册按钮指向列表页的segue(选中时会显示一条蓝色的线),按Delete键删除它。

2. 重新创建segue(从控制器到控制器)

从注册视图控制器的顶部导航栏(或者控制器本身)拖线到列表视图控制器,选择Show segue,然后在属性面板里设置segue的Identifier为registerToList(和你代码里的名称保持一致)。

3. 完善你的注册逻辑(避免崩溃+友好提示)

另外,你的代码里有几个新手常见的问题,建议优化:

@IBAction func registerButton(_ sender: Any) {
    // 先检查输入是否为空
    guard let email = emailField.text, !email.isEmpty, 
          let password = passwordField.text, !password.isEmpty else {
        // 给用户提示
        let alert = UIAlertController(title: "提示", message: "请填写邮箱和密码", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
        return
    }
    
    // 邮箱格式验证
    func isValidEmail(_ email: String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailPred.evaluate(with: email)
    }
    
    guard isValidEmail(email) else {
        let alert = UIAlertController(title: "提示", message: "邮箱格式不正确", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
        return
    }
    
    // 调用Firebase注册
    Auth.auth().createUser(withEmail: email, password: password) { [weak self] user, error in
        guard let self = self else { return }
        
        if let error = error {
            // 显示错误提示给用户,而不是只打印到控制台
            let alert = UIAlertController(title: "注册失败", message: error.localizedDescription, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "确定", style: .default))
            self.present(alert, animated: true)
            return
        }
        
        // 注册成功才跳转
        print("Registration successful")
        self.performSegue(withIdentifier: "registerToList", sender: self)
    }
}

这样修改后,只有当所有输入验证通过、Firebase注册成功时,才会触发跳转;任何环节出错都会停留在注册页,并给用户友好提示。

内容的提问来源于stack exchange,提问作者Matt Wong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:29:33