I want a \'$\' Sign in the text field which cannot be erased. A user should be able to enter values after it and if he presses backspace it should only erase the value he entere
As noted in the previous answer Add a prefix to UITextField
inside the textFieldDidBeginEditing
as delegate method i found using the following code to be best and right way to format string we are pre/post fixing currency symbols/codes
NSNumberFormatter* formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setPaddingPosition:NSNumberFormatterPadAfterPrefix];
[formatter setCurrencySymbol:symbol];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setCurrencyGroupingSeparator:@","];
[formatter setCurrencyDecimalSeparator:@"."];
-textField:shouldChangeCharactersInRange:replacementString:
and return NO
if the proposed change would delete the "$".Also, you might need to implement -textFieldDidBeginEditing:
to position the cursor after the "$" if it's not there already.
You can subclass UITextField
for all the text field which take amount as value.
class SpecialTextField: UITextField {
var amount: String {
get {
if self._amount.characters.count > 1 {
return (self._amount as NSString).substringFromIndex(2)
}
return ""
}
}
// MARK: - UITextField Observing
override internal func willMoveToSuperview(newSuperview: UIView!) {
if newSuperview != nil {
keyboardType = .DecimalPad
addTarget(self, action: #selector(SpecialTextField.didChangeText), forControlEvents: .EditingChanged)
}
}
override internal func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
return false
}
private var newVal: String = ""
private var _amount: String = ""
func didChangeText() {
if (text?.characters.count > 2) {
if text?.rangeOfString("$ ") == nil {
text = newVal
}
}
if (text?.characters.count == 1) && (text?.characters.count > newVal.characters.count) {
text = "$ " + text!
}
if (text?.characters.count == 2) && (text?.characters.count < newVal.characters.count) {
text = ""
}
newVal = text ?? ""
_amount = newVal
}
}
This will insert a $
sign whenever first number is entered, and removes it whenever all the numbers are removed.
var amount
will give the actual amount value user has entered, after removing the $
sign.
Hope this helped.
No need to use shouldChangeCharactersInRange delegate method. The easiest and most convenient solution is this
var label = UILabel(frame: CGRectMake(0, 0, 50, 50))
label.text = "$";
label.backgroundColor = UIColor(white: 0.0, alpha: 0.0)
tenantField.rightViewMode = .Always
tenantField.rightView = label