Skip to content

Instantly share code, notes, and snippets.

@kristofk
Last active January 18, 2023 12:27
Show Gist options
  • Save kristofk/8db00997da12a705a53a02267a0a9306 to your computer and use it in GitHub Desktop.
Save kristofk/8db00997da12a705a53a02267a0a9306 to your computer and use it in GitHub Desktop.
Custom reimplementation of textField(_:shouldChangeCharactersIn:replacamentString:)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text! as NSString
let newText = currentText.replacingCharacters(in: range, with: string)
textField.text = newText
return false
}
@AnatoliyOstapenko
Copy link

Hi Kristof,
Could you please explain why you return false in this case? Or is this a typo?

@kristofk
Copy link
Author

@AnatoliyOstapenko I return false because I'm handling the replacing of the text and I don't want the system to do anything.

However I forgot why I created this piece of code. In this form this code doesn't change anything you might as well not implement it. I guess that if you wanted manipulate the input of the user then this could be useful.

e.g. If you want to map keys on the keyboard to different characters. You can map "A" to "a" or a more sinister thing "A" to "b".

I'm sure I had something in mind for this code that I forgot.

@AnatoliyOstapenko
Copy link

Hi Kristof,
I have already figured it out) It’s interesting case. Thanks for replying

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment