skip to Main Content

I have textfield. It should allow just number but when I try to with autofill, I can choose contact name in contacts. How can I check is it numeric or not?

enter image description here

Then I can choose AutoFill and contacts. And I can choose contact name that textfield. I just want to check if is it number or not.

enter image description here

2

Answers


  1. You can use TextField’s shouldChangeCharactersIn function. Here is the code example:

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        let numericSet = CharacterSet.decimalDigits
        if let _ = string.rangeOfCharacter(from: numericSet.inverted) {
            // If the condition true that means string includes non-numeric character(s). So need to return false
            return false
        }
        
        return true
    }
    

    This function prevents non-numeric characters from being entered into the text field.

    Login or Signup to reply.
  2. I’m using it in my solution

    public func textFieldDidChangeSelection(_ textField: UITextField) {
         if let textEdit = textField.text {
             if Int(textEdit) == nil {
                 textField.text = oldValue
                 return
             }
          }
     }
    

    If it helps, adapt it to your case

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search