Skip to content

Instantly share code, notes, and snippets.

@infolock
Last active December 17, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infolock/5692830 to your computer and use it in GitHub Desktop.
Save infolock/5692830 to your computer and use it in GitHub Desktop.
UITextField delegate method shouldChangeCharactersInRange for allowing a valid currency value with the format of $x.xx. The following rules are enforced: 1) The value within the textField begins with a $ 2) Allows a decimal to be inserted only when there is 1 or more integers already in the field 3) Prevents more than 1 decimal to be inserted 4)…
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *textValue = textField.text;
if(textValue.length > 0 && string.length > 0) {
NSRange dotRange = [textValue rangeOfString:@"."];
BOOL isDot = [string isEqualToString:@"."];
if(isDot) {
return (dotRange.length == 0);
} else if(dotRange.length > 0) {
return (int) textValue.length - dotRange.location - 1 < 2;
}
return YES;
} else if(string.length == 0 && textValue.length > 1) {
return YES;
} else {
textField.text = @"$";
}
return NO;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment