Skip to content

Instantly share code, notes, and snippets.

@Aidan-Huang
Created May 19, 2014 11:54
Show Gist options
  • Save Aidan-Huang/4a8fb18892a4dde28f3d to your computer and use it in GitHub Desktop.
Save Aidan-Huang/4a8fb18892a4dde28f3d to your computer and use it in GitHub Desktop.
use in textfield number input only
// textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
- (BOOL)doesStringContainDecimal:(NSString*) string
{
NSString *searchForDecimal = @".";
NSRange range = [string rangeOfString:searchForDecimal];
//If we find a decimal return YES. Otherwise, NO
if (range.location != NSNotFound)
return YES;
return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
// allow backspace
if (range.length > 0 && [string length] == 0) {
return YES;
}
// do not allow . at the beggining
if (range.location == 0 && [string isEqualToString:@"."]) {
return NO;
}
// do not allow . if exist a .
if ([string isEqualToString:@"."] && [self doesStringContainDecimal:textField.text] == YES) {
return NO;
}
// set the text field value manually
NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string];
newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""];
textField.text = newValue;
// return NO because we're manually setting the value
return NO;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment