Skip to content

Instantly share code, notes, and snippets.

@NYiPhoneDeveloper
Created March 8, 2013 22:09
Show Gist options
  • Save NYiPhoneDeveloper/5120310 to your computer and use it in GitHub Desktop.
Save NYiPhoneDeveloper/5120310 to your computer and use it in GitHub Desktop.
UITextField allowing only 1 decimal and no decimals at the beginning
- (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;
}
// Comment out to allow decimal at the beginning
// do not allow . at the beggining
if (range.location == 0 && [string isEqualToString:@"."])
{
return NO;
}
// User already has 1 decimal -don't allow a second one.
if ( [textField.text rangeOfString: @"."].location == NSNotFound )
{
return YES;
}
else
{
// If entering __ANOTHER__DECIMAL__ don't allow it
if ( [string isEqualToString: @"."] )
{
return NO;
}
else // If its anything but another decimal -- allow it.
{
// 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