Skip to content

Instantly share code, notes, and snippets.

@Blackjacx
Last active December 28, 2023 17:18
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Blackjacx/2198d86442ec9b9b05c0801f4e392047 to your computer and use it in GitHub Desktop.
Save Blackjacx/2198d86442ec9b9b05c0801f4e392047 to your computer and use it in GitHub Desktop.
UITextField - Replace Text The Right Way
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let strippedString = <change replacements string so it fits your requirement - strip, trim, etc>
// replace current content with stripped content
if let replaceStart = textField.position(from: textField.beginningOfDocument, offset: range.location),
let replaceEnd = textField.position(from: replaceStart, offset: range.length),
let textRange = textField.textRange(from: replaceStart, to: replaceEnd) {
textField.replace(textRange, withText: strippedString)
}
return false
}
@AlexGee17
Copy link

Thank you a lot, dude!!!

@m3t8d1tr
Copy link

Thank you a lot, dude!!!

@tevonwallace
Copy link

This worked. Thank you

@karthisiva
Copy link

How do we handle back button and space bar pressed?

@Blackjacx
Copy link
Author

Blackjacx commented May 9, 2023

How do we handle back button and space bar pressed?

UIKit.UITextInput (which UITextfield conforms to) has the function deleteBackward which you can override in your UITextField subclass:

override func deleteBackward() {
    text = String(text?.dropLast() ?? "")
    sendActions(for: .editingChanged)
}

After that you have to programmatically trigger the editinChanged handler. This should do the trick. As you only delete text it shoiuld not be necessary to alter the new input text.

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