swift - Swift If 语句中的错误
问题描述
我设置了 4 个 UITextFields 和一个 UIButton。如果用户提供了用户名、电子邮件、密码等数据,这将作为一个注册页面工作。因此,只有并且只有在所有 UItextfields 不为空的情况下,才会启用注册按钮,以便用户可以点击内部并转到下一个界面视图。一切正常,但我注意到一个小错误,它正在进入我的最后一根神经 XD。
如果用户用所需的所有信息填写所有 UItextFields,但由于某种原因退格到其中一个,直到该字段为空,然后点击注册按钮,即使有一个空字段,注册也会成功。请我已经将近一个星期试图弄清楚这一点。
我设置 UIbotton 的方式:
private let registerButton : UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Registrar", for: .normal)
button.backgroundColor = UIColor.blue
button.layer.cornerRadius = 5
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
button.setTitleColor(.black, for: .normal)
button.addTarget(self, action: #selector(handleSignUp), for: .touchUpInside)
button.isEnabled = true
return button
}()
负责验证用户是否已填写所有字段的块代码。
@objc private func handleSignUp () {
let userName = userNameTexField.text
let email = emailTextField.text
let password = passwordTextField.text
let confirmPassword = confirmPasswordField.text
let birthDate = birthDateTextField.text
if userName?.isEmpty ?? true && email?.isEmpty ?? true && password?.isEmpty ?? true && confirmPassword?.isEmpty ?? true && birthDate?.isEmpty ?? true {
let alert = UIAlertController(title: nil, message: "Youmust fill all the fields with all the required infotmation to signup", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}else {
emailTextField.isUserInteractionEnabled = false
passwordTextField.isUserInteractionEnabled = false
confirmPasswordField.isUserInteractionEnabled = false
birthDateTextField.isUserInteractionEnabled = false
performSegue(withIdentifier: "goToHome", sender: nil)
print("LogIn succesful!")
print (userAge)
}
}
我希望修复此错误,因此当用户出于某种原因删除其中一个字段时,警报会再次弹出,告诉用户填写所有填充项以进行注册。
解决方案
您要求所有字段为空以触发警报。您需要知道其中一个是空的。尝试将 更改&&
为||
。
if userName?.isEmpty ?? true || email?.isEmpty ?? true || password?.isEmpty ?? true || confirmPassword?.isEmpty ?? true || birthDate?.isEmpty ?? true
推荐阅读
- c - 具有相同类型子对象的循环链表的父对象
- openlayers - Openlayers 6,从 GeoJSON 读取属性
- javascript - 节点。制作不和谐机器人时不工作
- google-cloud-storage - 无法获得 gsutil du 命令的准确结果
- python - 如何在 Python 中将数据框转换为奇数字典
- android - 如何使用 JetpackNavigation 组件从 BottomSheetDialogFragment 导航到另一个 Fragment
- join - GNU join 覆盖输出列
- git - 什么情况下git会删除未跟踪的文件?
- visual-studio - Librarian->Additional Dependencies 的用例是什么?
- django - 关系“survey_surveyuser”的“id”列中的空值违反非空约束