How to detect when user used AutoFill on a UITextField?

Hi,


Using ios11 autofill on my textfields works great, however I have a "Mobile number" field which I intend to only allow mobile numbers to be entered (ie. no letters), I have written logic in the "shouldChangeCharactersInRange" method to only allow numbers and "+" however this also blocks the autofill feature,

Is there any way to detect if the input is "autofill" and allow it to be entered,


Thanks

Replies

I had a similar issue when working with the Password Autofill feature in the iOS 12 beta. As far as I can tell, when users are inputting text, the length of the text returned in `shouldChangeCharactersInRange:replacementString:` is always 1, so I basically look for a length > 1 and assume that it has been either pasted or autofilled.

Sample code as per awe-mt suggestion. I use function textFieldDidChangeSelection method to find out user has used autofill. below is my sample code. Used Timer to let textFieldDidChangeSelection finish.

Code Block
var textFieldCountWhenBeginEditing = 0


Code Block
   func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    if let text = textField.text {
      textFieldCountWhenBeginEditing = text.count
    }
    return true
  }
func textFieldDidChangeSelection(_ textField: UITextField) {
    if textField.text != nil && textField != self.mobileTextField {
      let text = textField.text!
      let difference = abs(text.count - textFieldCountWhenBeginEditing)
      let isTextFromSuggestion = difference > 1 && !text.isEmpty
      if isTextFromSuggestion {
        Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { (_) in
           // Do something, its from autofill
        }
      }
      textFieldCountWhenBeginEditing = text.count
    }
  }