Last active
December 19, 2017 18:43
-
-
Save UjwalManjunath/6108632 to your computer and use it in GitHub Desktop.
Formatting number to Phone number Format as and when you type it in UItextfield
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ | |
int length = [[self formatNumber:[textField text]] length]; | |
if (length == 10) { | |
// [self textFieldShouldEndEditing:textField]; | |
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 setText:[NSString stringWithFormat:@"%@",[num substringToIndex:3]]]; | |
} | |
} | |
else if (length == 6) { | |
NSString *num = [self formatNumber:[textField text]]; | |
[textField setText:[NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]]]; | |
if (range.length > 0) { | |
[textField setText:[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:@""]; | |
int length = [mobileNumber length]; | |
if (length > 10) { | |
mobileNumber = [mobileNumber substringFromIndex: length-10]; | |
} | |
return mobileNumber; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment