Created
May 17, 2015 19:46
-
-
Save ahti/070c957d49589c13ca48 to your computer and use it in GitHub Desktop.
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
- (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