froggomad
froggomad

Reputation: 1915

Limit UITextField to Int input

I'm using shouldChangeCharactersIn to determine if the input of a given type of UITextField is an Int. No matter what character I input into said field, I get back:

input isn't a number

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if let numberField = textField as? NumberField {
        print("type is numberField")
        if Int(numberField.text!) != nil {
            print("input is a number")
            typoFrequencySaveOut.isEnabled = true
            typoFrequencySaveOut.backgroundColor = .green
            return true
        } else {
            print("input isn't a number")
            typoFrequencySaveOut.isEnabled = false
            typoFrequencySaveOut.backgroundColor = .lightGray
            return false
        }
    }
    print("type is not number field")
    return true
}

How else can I identify what data type is being entered into a UITextField?

Upvotes: 0

Views: 68

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119310

You need to check the input not entire text:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    ...
    var isEnglishNumber: Bool { return Int(string) != nil }
    print(isEnglishNumber ? "isEnglishNumber" : "isNOTEnglishNumber")
    ...
    return isEnglishNumber
}

Note that I removed codes that are not related to the original question, you can use the computed var isEnglishNumber in any way you like.

Upvotes: 1

Related Questions