Use the following code to manually add commas to desired places. You can get the logic from this code and customize it according to your requirements.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSLog(@"Text:%@textField length:%dRange.length:%lu , Range.location:%lu :: replacementString:%@",textField.text,textField.text.length,(unsigned long)range.length,(unsigned long)range.location,string); NSMutableString *tempString=textField.text.mutableCopy; int digitsCount; if ([string isEqualToString:@""]) //digit removed { NSLog(@"digit removed, string length after trimming:%d",[tempString stringByReplacingOccurrencesOfString:@"," withString:@""].length); digitsCount=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""].length-1; //digit removed }else ///digit added { digitsCount=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""].length+1 ; } NSLog(@"Number of digits:%d",digitsCount); switch (digitsCount) { //case 1:textField.text=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""]; //break; case 3:textField.text=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""]; break; case 4: //remove previous comma... tempString=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""].mutableCopy; [tempString insertString:@"," atIndex:1]; textField.text=tempString; break; case 5: //remove previous comma... tempString=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""].mutableCopy; [tempString insertString:@"," atIndex:2]; textField.text=tempString; break; case 6: //remove previous comma... tempString=[tempString stringByReplacingOccurrencesOfString:@"," withString:@""].mutableCopy; [tempString insertString:@"," atIndex:1]; [tempString insertString:@"," atIndex:4]; textField.text=tempString; break; default: break; } return YES; }
source share