I have a UITextField in my iOS app where I am already modifying the user's input. I realize now that I need to also make sure that the UITextField can hold a certain number of characters. I am implementing the delegate method as follows:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([[string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]
        isEqualToString:@""])
        return YES;
    NSString *previousValue = [[[textField.text stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""];
    string = [string stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSString *modifiedValue = [NSString stringWithFormat:@"%@%@", previousValue, string];
    if ([modifiedValue length] == 1) {
        modifiedValue = [NSString stringWithFormat:@"0.0%@", string];
    }
    else if ([modifiedValue length] == 2) {
        modifiedValue = [NSString stringWithFormat:@"0.%@%@", previousValue, string];
    }
    else if ([modifiedValue length] > 2) {
        modifiedValue = [NSString stringWithFormat:@"%@.%@",[modifiedValue substringToIndex: modifiedValue.length-2],[modifiedValue substringFromIndex:modifiedValue.length-2]];
    }
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:modifiedValue];
    modifiedValue = [formatter stringFromNumber:decimal];
    [textField setText:modifiedValue];
    return NO;
}
I am not sure with my code above how to factor in the limitation of 22 characters. Can anyone see what it is I need to do?
 
     
     
     
    