Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting text field entry to only one decimal point

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 ?

like image 496
utsabiem Avatar asked Nov 10 '11 07:11

utsabiem


2 Answers

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;
}
like image 186
user9930 Avatar answered Nov 06 '22 13:11

user9930


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);

}
like image 21
Paul Heller Avatar answered Nov 06 '22 12:11

Paul Heller