Swift UITextField 从第二个字符开始检查文本

Swift UITextField check text from second character

我有 ViewController,上面有 2 个文本字段。视图控制器是一个 UITextFieldDelegate。我检查此字段中的值,如果它们有效,则我从此视图控制器按钮激活 return。问题是验证从第二个字符开始:如果我尝试在每个字段中输入值,按钮将变为非活动状态,直到我输入第二个字符,但如果我在输入后删除该字符,return 按钮将保持活动状态。我发现问题是由 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 处的 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
    }

请在您的代码中添加此方法:

func textFieldDidEndEditing(textField: UITextField) {
    if textField == yourTextFieldName {  
        if textField.text?.characters.count > 0 {
            let _ = checkIfAddingAvailable()
        } else {
            addFoodButton.isEnabled = false
        }
    }
}