How do I format UITextField text in real time, while it's being edited?
Add a "textFieldDidChange" notification method to the text field control.
[textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange:(UITextField *)theTextField
{
NSLog(@"text changed: %@", theTextField.text);
NSString *textFieldText = [theTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithInt:[textFieldText integerValue]]];
textField.text=formattedOutput;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
if([string length]==0)
{
[formatter setGroupingSeparator:@","];
[formatter setGroupingSize:4];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:3];
NSString *num = textField.text ;
num = [num stringByReplacingOccurrencesOfString:@"," withString:@""];
NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
textField.text = str;
return YES;
}
else {
[formatter setGroupingSeparator:@","];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:3];
NSString *num = textField.text ;
if(![num isEqualToString:@""])
{
num = [num stringByReplacingOccurrencesOfString:@"," withString:@""];
NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
textField.text = str;
NSLog(@"add:%@",str);
}
return YES;
}
}
P.S. This code is in ARC
, take care of memory management in non arc environment.