在输入时逐字母地验证UITextField文本
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在输入时逐字母地验证UITextField文本相关的知识,希望对你有一定的参考价值。
所以我对我的文本域进行了验证,如果验证为真,我的按钮将被启用,如果验证为假,我的按钮将被禁用。问题是验证仅在我单击键盘中的完成按钮后运行。
我想逐字逐句地进行验证检查。
这是我的代码:
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)
}
}
答案
您还可以将其作为IBAction从故事板连接(如果您使用的是故事板)
附:不要忘记将类型更改为UITextField,并将事件更改为ValueChanged。
另一答案
您应该使用不同的委托方法 -
文本框(_: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
}
以上是关于在输入时逐字母地验证UITextField文本的主要内容,如果未能解决你的问题,请参考以下文章
如何在播放该歌曲的声音文件时逐字母读取python中的歌曲[关闭]