我有 ViewController,上面有 2 个文本字段。 View Controller 是一个 UITextFieldDelegate。我检查此字段中的值,如果它们有效,则激活此 View Controller 按钮的返回。问题是验证是从第二个字符开始的:如果我尝试在每个字段中输入值,按钮将变为非事件状态,直到我输入第二个字符,但如果我在输入后删除该字符,返回按钮将保持事件状态。我发现问题是由 checkIfAddingAvailable()
引起的。我哪里错了?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldTextString = textField.text else {
return true
}
let oldText = oldTextString as NSString
let newString = oldText.replacingCharacters(in: range, with: string) as NSString
if newString.length > 0 {
let _ = checkIfAddingAvailable()
} else {
addFoodButton.isEnabled = false
}
return true
}
func checkIfAddingAvailable() -> Bool {
//TODO: implement valid checking of posibility to add food
guard let foodName = foodNameField.text else { return false }
guard !foodName.isEmpty else {
return false
}
guard let foodShelfLife = shelfLifeField.text else { return false }
guard !foodShelfLife.isEmpty else {
return false
}
guard let foodShelfLifeIntoDouble = Double(foodShelfLife) else { return false }
guard foodShelfLifeIntoDouble > 0 else {
return false
}
addFoodButton.isEnabled = true
return true
}
最佳答案
您应该在 shouldChangeCharactersIn 处将 newstring 传递给 checkIfAddingAvailable,因为 textField 还没有最终文本
调整文本字段的代码
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldTextString = textField.text else {
return true
}
let oldText = oldTextString as NSString
let newString = oldText.replacingCharacters(in: range, with: string) as NSString
if newString.length > 0 {
let _ = checkIfAddingAvailable(newString)
} else {
addFoodButton.isEnabled = false
}
return true
}
func checkIfAddingAvailable(_ foodNameFieldText :String) -> Bool {
//TODO: implement valid checking of posibility to add food
guard let foodName = foodNameFieldText else { return false }
guard !foodName.isEmpty else {
return false
}
guard let foodShelfLife = shelfLifeField.text else { return false }
guard !foodShelfLife.isEmpty else {
return false
}
guard let foodShelfLifeIntoDouble = Double(foodShelfLife) else { return false }
guard foodShelfLifeIntoDouble > 0 else {
return false
}
addFoodButton.isEnabled = true
return true
}
关于ios - Swift UITextField 检查第二个字符的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45819381/