文字输入期间的文字字段验证

时间:2018-05-26 15:51:36

标签: ios swift swift4

我正在掌握文本字段功能,可以让您检查" didEndEditing"或者" shouldStartEditing"发生。

当我有2个文本字段和一个按钮时,我的工作正常。如果我想在进行一些验证后启用按钮,我会使用" didEndEditing"如果用户点击其他字段时一切正常,则进行一些验证并启用按钮。

问题如果页面上只有一个文本字段和一个按钮,我只需要在启用按钮之前在文本字段中输入整数,我该如何实现?

即。按钮被禁用。当我在文本字段中输入文本时,如果只有整数,则启用按钮。如果您正在输入其他任何内容,请不要实时填写。

由于只有一个文本字段,我不认为我可以使用" didEndEditing"因为你永远不会离开'文本字段(没有其他内容可供点击)

我尝试过什么我试过这个:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print("While entering the characters this method gets called")
    if textField === timeInputField {

//set which characters are valid
        let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted


//if text isn't empty then hide the error label ("must input a time")             
        if timeInputField.text?.isEmpty == false {
            timeInputErrorLabel.isHidden = true
        }

//if the string returns values in the range set button to enabled
        return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil
    } else {
        doWorkoutButtonOutlet.isEnabled = true
    }
    return true
}

我认为我实际上是想在Swift 4中实现这个Need to enable button when text is entered in field.

1 个答案:

答案 0 :(得分:1)

这将阻止整数进入textField以外的任何其他内容。如果使用多个textField,请不要忘记检查{。}}。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    if numbers.contains(string ?? "") {
        // Validate text for button enabling
        if let stringValue = textField.text {
            if let number = Int(stringValue) {
                yourButton.isEnabled = true
                // Text validated as an integer. Can use value of number if desired
            } else {
                yourButton.isEnabled = false
            }
        } else {
            yourButton.isEnabled = false
        }
        // Return true to update field with new character
        return true
    } else {
        // Return false as entered character is not a digit 0-9
        return false
    }
}

您还可以使用此委托方法验证文本:

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    if let stringValue = textField.text {
        if let number = Int(stringValue) {
            yourButton.isEnabled = true
            // Do something with number value
            return true
        }
    }
    return false
}
相关问题