Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
DevC Avatar asked Nov 21 '13 13:11

DevC


People also ask

How do I restrict Uitextfield to take only numbers in Swift?

Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

How do you check if a string contains only digits Swift?

To check whether the string contains only numbers, we use the concept of set and CharacterSet. decimalDigits together. For a string to contains only a number, all the characters in that string must be a subset of CharacterSet. decimalDigits .


2 Answers

In Swift 3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let allowedCharacters = "0123456789!@#$%^&*()_+~:{}|\"?><\\`,./;'[]=-"
    return allowedCharacters.contains(string) || range.length == 1
}
like image 151
Charlton Provatas Avatar answered Oct 06 '22 22:10

Charlton Provatas


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;
}
like image 23
Kalpesh Avatar answered Oct 06 '22 22:10

Kalpesh