Skip to content

Instantly share code, notes, and snippets.

@ThinhPhan
Last active October 29, 2015 05:16
Show Gist options
  • Save ThinhPhan/2a0dcccd3123e824a391 to your computer and use it in GitHub Desktop.
Save ThinhPhan/2a0dcccd3123e824a391 to your computer and use it in GitHub Desktop.
UITextField should allow only numbers.
#define ACCEPTABLE_CHARACTERS @"0123456789"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (!string.length)
return YES;
if (textField == self.quantityTextField) {
NSCharacterSet *numbersOnly = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:numbersOnly] componentsJoinedByString:@""];
BOOL stringIsValid = [string isEqualToString:filtered];
return stringIsValid;
}
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment