DevC DevC - 1 month ago 9
iOS Question

UITextField - Allow only numbers and punctuation input/keypad

I have tried the code below but that only allows for numbers on the keypad to be inputted. My app requires the keypad to use a period/full stop (for money transactions). The code I tried is:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound)
{
return NO;
}
return YES;

}


Thanks for any help.

Answer

Try this

Make a macro

#define ACCEPTABLE_CHARECTERS @"0123456789."

And use it

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    if (textField==textFieldAmount)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];
    }
    return YES;
}
Comments