UITextField and NSFormatter subclasses for formatting phone numbers. Allow different formats for different countries(patterns). Caret positioning works excellent.
Swift version is here - https://github.com/Serheo/PhoneNumberFormatter
Use any of next methods:
- use embedded framework /SHSPhoneComponents/SHSPhoneComponent.xcodeproj (iOS 8 )
- pod 'SHSPhoneComponent'
- copy /SHSPhoneComponents/Library folder to your project.
And import "SHSPhoneLibrary.h" on your Controller.
If you need complete example please see 'Example_iOS7 ' or 'Example_iOS8 embedded' folders.
[self.phoneField.formatter setDefaultOutputPattern:@" # (###) ###-##-##"];
You can set prefix on all inputs:
[self.phoneField.formatter setDefaultOutputPattern:@"(###) ###-##-##"];
self.phoneField.formatter.prefix = @" 7 ";
[self.phoneField.formatter setDefaultOutputPattern:@"##########" imagePath:nil];
[self.phoneField.formatter addOutputPattern:@" # (###) ###-##-##" forRegExp:@"^7[0-689]\\d*$" imagePath:@"flagRU"];
[self.phoneField.formatter addOutputPattern:@" ### (##) ###-###" forRegExp:@"^374\\d*$" imagePath:@"flagAM"];
[self.phoneField.formatter setDefaultOutputPattern:@"### ### ###"];
self.phoneField.formatter.prefix = @" 7 ";
[self.phoneField.formatter addOutputPattern:@"(###) ###-##-##" forRegExp:@"^1\\d*$" imagePath:@"SHSPhoneImage.bundle/flag_ru"];
[self.phoneField.formatter addOutputPattern:@"(###) ###-###" forRegExp:@"^2\\d*$" imagePath:@"SHSPhoneImage.bundle/flag_ua"];
If you want to format some numbers in specific way just do
[self.phoneField.formatter addOutputPattern:@" # (###) ###-##-##" forRegExp:@"^7[0-689]\\d*$" imagePath:@"flagRU"];
[self.phoneField.formatter addOutputPattern:@" ### (##) ###-###" forRegExp:@"^374\\d*$" imagePath:@"flagAM"];
If you need only formatting function you can use SHSPhoneNumberFormatter class. For additional class info see http://serheo.github.io/SHSPhoneComponent/
if you are using any predictions/suggestion in the textfield, set hasPredictiveInput flag to YES.
ARC Enabled. iOS 7
SHSPhoneComponent is available under the MIT license. See the LICENSE file for more info.