我正在做Swift iOS应用程序。在这个应用中,我有一些注册屏幕。我的要求是不允许用户使用双空格,如果文本字段是空的,也要限制用户使用单空格。如果文本字段中有一个字符,用户可以给一个空格。
但是,一旦三个文本字段都填满了,那么只有我必须启用以下功能。完成 按钮,但即使单个文本字段是空的,我也必须禁用 "完成 "按钮。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let rawString = string
let range = rawString.rangeOfCharacter(from: .whitespaces)
if ((textField.text?.count)! == 0 && range != nil)
|| ((textField.text?.count)! > 0 && textField.text?.last == " " && range != nil) {
return false
}
self.doneButtonEnable()
return true
}
func doneButtonEnable() {
if ((firstNameTextField.text!.count > 0) && (lastNameTextField.text!.count > 0) && (displayNameTextField.text!.count > 0)) {
doneButtonAppearance(appearance: true)
doneButton.setBackgroundImage(UIImage(named:"image_enable"), for: .normal)
} else {
doneButtonAppearance(appearance: false)
doneButton.setBackgroundImage(UIImage(named:"image_disabled"), for: .normal)
}
}
问题是,如果我在所有3个文本字段中输入一个字符,每个文本字段有1个字符,按钮仍然显示为禁用,如果我在最后一个文本字段中输入2个字符,那么只有 "完成 "按钮是启用的。
另外,如果我在第3个文本字段中删除了全部文本,它应该禁用 "完成 "按钮,但是,在控制台中,它显示的是最后输入文本的最后一个字符。
这是我面临的问题。
有什么解决办法吗?
问题是你调用 self.doneButtonEnable()
在编辑时,在textField完成之前,意味着你在func'shouldChangeCharactersIn'中输入's'。意味着你在func'shouldChangeCharactersIn'中输入's',在 self.doneButtonEnable()
行,textField.text不会在其文本中添加's'。所以只要延迟这个函数就可以了。试试下面的代码。
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.doneButtonEnable()
}