Skip to content

Instantly share code, notes, and snippets.

@UjwalManjunath
Last active December 19, 2017 18:43
Show Gist options
  • Save UjwalManjunath/6108632 to your computer and use it in GitHub Desktop.
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
- (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