iOS: when user select QuickType keyboard handle selected UITextField

187 Views Asked by At

In my project when user select specific UITextField (that UITextField supposed to get user telephone number), the QuickType Keyboard show user telephone number. I want when user select his/her telephone number I can change that (remove "+" in telephone number) and show the result in that UITextField. how can I do that?

UPDATE:

I tried shouldChangeCharactersIn (UITextFieldDelegate function) to handle that, but replacementString return space (" ") and if I just return true (doing nothing inside that function) to that nothing will show inside UITextField.

2

There are 2 best solutions below

0
Phil Dukhov On

You were on the right track with shouldChangeCharactersIn, but in case with QuickType keyboard it gets called two times instead of one.

First call is made to clean the current string, even when it's empty: range is (0, 0) in this case. Not much sence, but if you type something, select whole text, and paste phone number from quick help, this first change will have range of the full string to clear it.

And to modify input string, you need to update text field text and return false, because you don't need system to update text anymore.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.starts(with: "+") {
        let modifierString = String(string.dropFirst())
            .trimmingCharacters(in: .whitespacesAndNewlines)
        textField.text = ((textField.text ?? "") as NSString)
            .replacingCharacters(in: range, with: modifierString)
        return false
    } else {
        return true
    }
}

Note that it'll also ignore press of "+" made by user, if you don't want that you probably need to add more logic to that if, like

if string.count > 1 && string.starts(with: "+") {

This will allow user to press "+" but remove it from any pasted content.

0
Alex Aghajanov On

If your objective is to remove any extra characters and keep only numbers, you could in the first place restrict the user to inputting only numbers by selecting the "Number Pad" keyboard type in the attributes inspector of the text field in the storyboard.

Attributes inspector

Or if you'd like to do it with code:

textField.keyboardType = .numberPad

Sorry if this is not what you are looking for, I just thought maybe you overcomplicated the problem and resorted to filtering the text to numbers, when there is an Apple-provided type of keyboard exactly for collecting phone numbers that you could use instead.