ios - 如何在 UIAlertController 中验证电子邮件地址?
问题描述
我正在尝试设置此 UIAlertController,以便在输入正确的电子邮件地址之前,“注册”按钮不会变为活动状态。(包含@符号)。
关于如何做到这一点的任何建议?尝试了其他文章,但解决方案不起作用,这里是 Swift newb。
我已包含以下代码:
@IBAction func loginTapped(_ sender: UIButton) {
//The user is not logged in, so prompt for their email address
let loginAlert = UIAlertController(title: "Sign Up For LivNao", message:
"Please enter your email address to join the LivNao study",
preferredStyle: UIAlertController.Style.alert)
loginAlert.addAction(UIAlertAction(title: "Cancel", style:
UIAlertAction.Style.cancel, handler: nil))
loginAlert.addAction(UIAlertAction(title: "Sign Up", style:
UIAlertAction.Style.default, handler: {
(action: UIAlertAction) in
self.handleLogin(loginAlert)
}))
loginAlert.addTextField { (textField : UITextField) in
textField.placeholder = "Enter email"
}
loginAlert.view.setNeedsLayout()
self.present(loginAlert, animated: true, completion: nil)
}
解决方案
看一下这个。
var signUp: UIAlertAction!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let loginAlert = UIAlertController(title: "Sign Up For LivNao", message: "Please enter your email address to join the LivNao study", preferredStyle: UIAlertController.Style.alert)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
loginAlert.addAction(cancel)
signUp = UIAlertAction(title: "Sign Up", style: UIAlertAction.Style.default, handler: { (action: UIAlertAction) in
//self.handleLogin(loginAlert)
})
loginAlert.addAction(signUp)
loginAlert.addTextField { (textField : UITextField) in
textField.placeholder = "Enter email"
textField.delegate = self
}
signUp.isEnabled = false
loginAlert.view.setNeedsLayout()
self.present(loginAlert, animated: true, completion: nil)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
signUp.isEnabled = isValidEmail(testStr: textField.text!) ? true : false
return true;
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
推荐阅读
- node.js - Azure 构建上的 JavaScript 堆内存不足
- compilation - gnuplot gsl 编译链接
- vb.net - 如何调用从 mdiparent 调用 mdichildB 方法的 mdichildA 方法
- vue.js - vue beforeMount 事件无法正常工作
- javascript - 在位于 SRC 文件夹的 index.html 文件中注册一个服务工作者 - ReactJS
- c - 将数据从 SVGimage 格式转换为 xmlDocPtr 共振峰的函数错误
- java - 在 Jtree 中转换字符串
- react-navigation - 使用 React Navigation 5 在选项卡双击时重置选项卡内的堆栈
- python - 类型错误'numpy.float64'没有我无法解决的len(),说服Python它正在处理一个数组?
- excel - 如何加快在共享文件中运行的 excel 宏?