因此我对我的文本字段进行了验证,如果验证为true,则将启用我的按钮,如果验证为false,则将禁用我的按钮。问题是只有在单击键盘上的“完成”按钮后才能运行验证。
我要一个字母一个字母地进行验证检查。
这是我的代码:
func textFieldDidEndEditing(_ textField: UITextField) {
if (nomorTextField.text!.count >= 10) {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
if(nomorTextField.text!.count > 13) {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
else if emailTextFeild.text == "" {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
}
else if emailTextFeild.text?.isEmail == false {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
}
else {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
您应该使用其他委托方法-
textField(_:shouldChangeCharactersIn:replacementString:)
在文本字段中更改字符之前立即调用此方法。您应该始终返回true,因为在您的情况下,您不想阻止文本编辑。但是,您确实需要使用新字符更新已编辑的文本字段文本,以确保计数正确。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Casting String as NSString to be able to replace characters using NSRange easily.
guard let text = textField.text as NSString? else { return true }
// Get the length of the final text
let finalTextCount = text.replacingCharacters(in: range, with: string).count
// Setup the text count for the field depending on which one was edited
let nomorTextFieldCount = textField == nomorTextField ? finalTextCount :
nomorTextField.text!.count
if nomorTextFieldCount >= 10 {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
if nomorTextFieldCount > 13 {
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}else if emailTextFeild.text == "" {
nextButton.isEnabled = true
nextButton.backgroundColor = #colorLiteral(red: 1, green: 0.4431372549, blue: 0.003921568627, alpha: 1)
}else if emailTextFeild.text?.isEmail == false{
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
}else{
nextButton.isEnabled = false
nextButton.backgroundColor = #colorLiteral(red: 0.662745098, green: 0.662745098, blue: 0.662745098, alpha: 1)
}
return true
}