Last active
December 17, 2015 23:58
-
-
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)…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(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