I have created a text field to enter an amount of money. I want the user to be able to enter only one decimal point. I implemented that in the -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
method.
In the general case it works fine, but if backspace is pressed and the single decimal point is deleted, after that it still assumes that a decimal point has been entered, and so does not accept the decimal point again.
I need to reset the decimalPointEntered
flag whenever the decimal point is deleted by pressing backspace. How to do that ?
This works fine for me. Try this code:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count] >= 2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
return !([sepStr length]>1);
}
return YES;
}
Here is what I use:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (!numberFormatter) {
numberFormatter = [[NSNumberFormatter alloc]init];
//[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
}
NSNumber *test = [numberFormatter numberFromString:[self.text stringByAppendingString: string]]; // in case we entered two decimals
return (test != nil);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With