9

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.

DevC
  • 6,982
  • 9
  • 45
  • 80

4 Answers4

44

Try this

Make a macro

#define ACCEPTABLE_CHARACTERS @"0123456789."

And use it

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

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

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

        return [string isEqualToString:filtered];
    }
    return YES;
}
Ogre Codes
  • 18,693
  • 1
  • 17
  • 24
Kalpesh
  • 5,336
  • 26
  • 41
3

In Swift 3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = "0123456789!@#$%^&*()_+~:{}|\"?><\\`,./;'[]=-"
    return allowedCharacters.contains(string) || range.length == 1
}
Charlton Provatas
  • 2,184
  • 25
  • 18
2

Just use

[textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];

after creating your textfield.

LifeIsHealthy
  • 347
  • 1
  • 8
  • 2
    this does not prevent the user from changing to the `ABC` keyboard. – DevC Nov 21 '13 at 13:44
  • @Gman Well I guess there is no standard keyboard that fully meets your requirements... I guess you'd have to make your own input view for that purpose though that seems like an overkill to me. – LifeIsHealthy Nov 21 '13 at 13:48
  • It also doesn't defend from pasting incorrect data into a textField – FreeNickname Sep 30 '15 at 08:22
2

How about a custom character set? Something like this:

NSCharacterSet *testChars = [NSCharacterSet characterSetWithCharactersInString:@"0123456789+*#-() "];

Because setting the keyboard type is pretty useless on iPad...

Laszlo
  • 2,803
  • 2
  • 28
  • 33