Skip to content

Instantly share code, notes, and snippets.

@ReDetection
Forked from gdavis/gist:2845766
Created September 25, 2014 11:00
Show Gist options
  • Save ReDetection/e2cbbaf730493b788909 to your computer and use it in GitHub Desktop.
Save ReDetection/e2cbbaf730493b788909 to your computer and use it in GitHub Desktop.
fixed conversion warning
#pragma mark - Phone Number Field Formatting
// Adopted from: http://stackoverflow.com/questions/6052966/phone-number-formatting
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.mobileNumberField || textField == self.homeNumberField || textField == self.workNumberField) {
int length = [self getLength:textField.text];
if(length == 10) {
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.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
}
else if(length == 6) {
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [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:@""];
NSUInteger length = [mobileNumber length];
if(length > 10) {
mobileNumber = [mobileNumber substringFromIndex: length-10];
}
return mobileNumber;
}
-(int)getLength:(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];
return length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment