I have a text field where the user enters data. It's a phone number field. If the user enters 1234567890
, I want it displayed as (123)-(456)-7890
as the user types. How is this possible?
Answer: A: If you have not added the spaces then it is quite normal. The spaces are added by the Country Code using the countries' Phone number format on an iPhone.
This will help you
Format (xxx) xxx-xxxx
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { int length = (int)[self getLength:textField.text]; //NSLog(@"Length = %d ",length); if(length == 10) { if(range.length == 0) return NO; } if(length == 3) { NSString *num = [self formatNumber:textField.text]; textField.text = [NSString stringWithFormat:@"(%@) ",num]; if(range.length > 0) textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]]; } else if(length == 6) { NSString *num = [self formatNumber:textField.text]; //NSLog(@"%@",[num substringToIndex:3]); //NSLog(@"%@",[num substringFromIndex:3]); textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]]; if(range.length > 0) textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]]; } return YES; } - (NSString *)formatNumber:(NSString *)mobileNumber { mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""]; NSLog(@"%@", mobileNumber); int length = (int)[mobileNumber length]; if(length > 10) { mobileNumber = [mobileNumber substringFromIndex: length-10]; NSLog(@"%@", mobileNumber); } return mobileNumber; } - (int)getLength:(NSString *)mobileNumber { mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""]; mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""]; int length = (int)[mobileNumber length]; return length; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With