Live phone number format using NBAsYouTypeFormatter

I've searched all over the place and I've seen many solutions for this, but most of them are really "hacky" and error prone.

I am trying to format a phone number on a UITextField using the IOS class of the libPhoneNumber NBAsYouTypeFormatter class.

However, I have not been able to find the correct way to use it.

Below is my attempt. (From this thread ios phone number format )

      var asYouTypeFormatter = NBAsYouTypeFormatter(regionCode: "US");

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == phoneTextField {
        if range.length == 0 {
            textField.text = asYouTypeFormatter.inputDigit(textField.text + string);
        }
        else if range.length == 1 {
            textField.text = asYouTypeFormatter.removeLastDigit();
        }
        return false;
    }
    return true;
}

      

This code is indeed detecting range.length

, and it does not take into account that if the user selects one or more characters and then type.

If the user does this, it will result in him not being a type.

Has anyone found a more elegant method for this problem?

+3


source to share





All Articles