Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

AlexGee17 commented Jun 1, 2017

Thank you a lot, dude!!!

@m3t8d1tr
Copy link

m3t8d1tr commented Aug 24, 2021

Thank you a lot, dude!!!

@tevonwallace
Copy link

tevonwallace commented Aug 29, 2021

This worked. Thank you

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