Skip to content

Instantly share code, notes, and snippets.

@ahti
Created May 17, 2015 19:46
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 ahti/070c957d49589c13ca48 to your computer and use it in GitHub Desktop.
Save ahti/070c957d49589c13ca48 to your computer and use it in GitHub Desktop.
- (void)viewDidLoad
{
self.formatter = [NSNumberFormatter new];
self.formatter.numberStyle = NSNumberFormatterCurrencyStyle;
self.formatter.partialStringValidationEnabled = YES;
self.textField.delegate = self;
self.textField.text = [self.formatter editingStringForObjectValue:self.number];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *oldString = textField.text;
NSString *newString = [oldString stringByReplacingCharactersInRange:range withString:string];
NSRange newRange = NSMakeRange(range.location + string.length, 0);
NSString *error;
BOOL isValid = [self.formatter isPartialStringValid:&newString
proposedSelectedRange:&newRange
originalString:oldString
originalSelectedRange:range
errorDescription:&error];
NSLog(@"valid: %@, error: %@", isValid?@"YES":@"NO", error);
self.textField.text = newString;
UITextPosition *startPos = [textField positionFromPosition:textField.beginningOfDocument offset:newRange.location];
UITextPosition *endPos = [textField positionFromPosition:startPos offset:newRange.length];
[textField setSelectedTextRange:[textField textRangeFromPosition:startPos toPosition:endPos]];
return NO;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment