Skip to content

Instantly share code, notes, and snippets.

@abbeyjackson
Last active July 21, 2016 21:18
Show Gist options
  • Save abbeyjackson/71ff9eee5130dcbc515073211ffd644c to your computer and use it in GitHub Desktop.
Save abbeyjackson/71ff9eee5130dcbc515073211ffd644c to your computer and use it in GitHub Desktop.
Add $ or anything else to beginning of UITextField. The following will prepend a $ when the user types in a textfield and have it deleted when the user deletes their last character
func setUpPriceTextField() {
priceTextField.delegate = self
priceTextField.addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged)
}
// MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
if textField.text == "$0" {
textField.text = "$"
}
}
func textFieldDidChange(textField: UITextField){
guard let text = textField.text else { return }
if text.removeCharactersInString("$").isEmpty {
textField.text = ""
}
if !text.hasPrefix("$") {
textField.text = "$" + text
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let currentCharacterCount = text.removeCharactersInString("$").characters.count
let newLength = currentCharacterCount + string.characters.count - range.length
if string.containsOnlyCharactersInString("$0123456789") && newLength <= 3 {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment