UITextField - allow only numbers and punctuation / keyboard

I tried the code below, but only for entering numbers on the keyboard. My application requires the keyboard 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.

+7
ios numbers iphone-keypad
source share
4 answers

try it

Make 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; } 
+41
source share

Just use

 [textField setKeyboardType:UIKeyboardTypeNumbersAndPunctuation]; 

after creating the text box.

+2
source share

How about a custom character set? Something like that:

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

Because setting a keyboard type is pretty useless on an iPad ...

+2
source share

In Swift 3:

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

All Articles