Last active
July 21, 2016 21:18
-
-
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
This file contains hidden or 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 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