Last active
December 28, 2023 17:18
-
-
Save Blackjacx/2198d86442ec9b9b05c0801f4e392047 to your computer and use it in GitHub Desktop.
UITextField - Replace Text The Right Way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Thank you a lot, dude!!!
This worked. Thank you
How do we handle back button and space bar pressed?
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
Thank you a lot, dude!!!