Skip to content

Instantly share code, notes, and snippets.

@AndrewBarba
Created July 29, 2014 21:52
Show Gist options
  • Save AndrewBarba/6f7f9e5e508df0601503 to your computer and use it in GitHub Desktop.
Save AndrewBarba/6f7f9e5e508df0601503 to your computer and use it in GitHub Desktop.
/**
* @updated: 2014-07-29
* @source: http://stackoverflow.com/questions/6052966/phone-number-formatting
*/
-(NSString*)phoneNumberString
{
static NSCharacterSet* set = nil;
TL_DISPATCH_ONCE(^{
set = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
});
NSString* phoneString = [[self componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
switch (phoneString.length) {
case 4:
case 5:
case 6:
return [NSString stringWithFormat:
@"(%@) %@",
[phoneString substringToIndex:3],
[phoneString substringWithRange:NSMakeRange(3, phoneString.length-3)]];
case 7:
case 8:
case 9:
case 10:
return [NSString stringWithFormat:
@"(%@) %@-%@",
[phoneString substringToIndex:3],
[phoneString substringWithRange:NSMakeRange(3, 3)],
[phoneString substringFromIndex:6]];
case 11:
return [NSString stringWithFormat:
@"%@ (%@) %@-%@",
[phoneString substringToIndex:1],
[phoneString substringWithRange:NSMakeRange(1, 3)],
[phoneString substringWithRange:NSMakeRange(4, 3)],
[phoneString substringFromIndex:7]];
case 12:
return [NSString stringWithFormat:
@"+%@ (%@) %@-%@",
[phoneString substringToIndex:2],
[phoneString substringWithRange:NSMakeRange(2, 3)],
[phoneString substringWithRange:NSMakeRange(5, 3)],
[phoneString substringFromIndex:8]];
default: return phoneString;
}
}
// UITextField Usage
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.phoneNumberTextField) {
NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
textField.text = text.phoneNumberString; // implemented as a category on NSString
return NO;
}
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment