Objective-C: Numbers only text field? [duplicate]
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {/* for backspace */ if([string length]==0){ return YES; }/* limit to only numeric characters */ NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; for (int i = 0; i < [string length]; i++) { unichar c = [string characterAtIndex:i]; if ([myCharSet characterIsMember:c]) { return YES; } }return NO;}
The code is somehow incorrect, should be
/* limit to only numeric characters */NSCharacterSet* numberCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];for (int i = 0; i < [string length]; ++i){ unichar c = [string characterAtIndex:i]; if (![numberCharSet characterIsMember:c]) { return NO; }}return YES;
The following code will allow you to only input numbers as well as limit the amount of characters that can be used.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { /* limit to only numeric characters */ NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; for (int i = 0; i < [string length]; i++) { unichar c = [string characterAtIndex:i]; if ([myCharSet characterIsMember:c]) { return YES; } } /* limit the users input to only 9 characters */ NSUInteger newLength = [customTextField.text length] + [string length] - range.length; return (newLength > 9) ? NO : YES;}