Here is how I achieved that. I am going to explain from scratch. So, new users can get the way from scratch.
Download libPhoneNumber-iOS library from here. At the bottom side of the page of that link, you will find what files you need to add to your project.
Your bundle should look like this:
Now, follow below steps to implement.
(1) Import files in the view controller where you need your textfield to be formatted.
#import "NBPhoneMetaDataGenerator.h"
#import "NBPhoneNumberUtil.h"
#import "NBAsYouTypeFormatter.h"
and make instance of type NBAsYouTypeFormatter in header file:
NBAsYouTypeFormatter *asYouTypeFormatter;
(2) In the viewDidLoad method of that view controller, initialize that object taken earlier:
asYouTypeFormatter = [[NBAsYouTypeFormatter alloc] initWithRegionCode:@"IN"];
Note: @"IN" is for India. You can set it to anything you want. Refer to plist file that will be included in libPhoneNumber-iOS library to view full list of region codes.
(3) In delegate method of UITextField, dynamically manage text of yout textfield.
#pragma mark
#pragma mark - Phone Number textfield formatting
# define LIMIT 18 // Or whatever you want
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Just allow 18 digits
if(!(([string length] + range.location) > LIMIT))
{
// Something entered by user
if(range.length == 0)
{
[textNumber setText:[self.asYouTypeFormatter inputDigit:string]];
}
// Backspace
else if(range.length == 1)
{
[textNumber setText:[self.asYouTypeFormatter removeLastDigit]];
}
}
return NO;
}
Hope it helps others !!!