我创建了一个函数,该函数在UITextField的右侧显示错误,例如电子邮件无效,带有坏字符,我想在用户实时打字时显示错误,而不是在用户完成写作时显示错误,但我似乎无法弄清楚,图像在用户开始再次打字后也不会自行删除,它只是停留在那里。
如果有人知道我如何在用户输入时显示错误,以及如何在显示错误后开始输入时删除它,这将有助于我和未来的swiftians。
代码:
func setPaddingView(strImgname: String,txtField: UITextField){
let imageView = UIImageView(image: UIImage(named: "cross"))
imageView.frame = CGRect(x: 0, y: 0, width: imageView.image!.size.width , height: imageView.image!.size.height)
let paddingView: UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
paddingView.addSubview(imageView)
txtField.rightViewMode = .always
txtField.rightView = paddingView
}
func textFieldDidEndEditing(_ textField: UITextField)
{
if (textField == firstNameFieldSignUp)
{
let name_reg = "[A-Za-z0-9]{2,20}"
let name_test = NSPredicate(format: "SELF MATCHES %@", name_reg)
if name_test.evaluate(with: firstNameFieldSignUp.text) == false
{
self.setPaddingView(strImgname: "cross", txtField: firstNameFieldSignUp)
}
}
if (textField == lastNameFieldSignUp)
{
let name_reg = "[A-Za-z0-9]{3,20}"
let name_test = NSPredicate(format: "SELF MATCHES %@", name_reg)
if name_test.evaluate(with: lastNameFieldSignUp.text) == false
{
self.setPaddingView(strImgname: "cross", txtField: lastNameFieldSignUp)
}
}
@ioslifertextFieldDidEndEditing
在textfield结束编辑(辞职)时被调用,将目标添加到viewDidload()
上的textfield可能会帮助您获得预期的结果
textField.addTarget(self, action: #selector(textDidChange(_:)), for: .valueChanged)
@objc func textDidChange(_ sender: UITextField) {
// validation logic here
}