Created
August 20, 2014 20:31
-
-
Save frankus/e9660a376451f21e73f3 to your computer and use it in GitHub Desktop.
Pretty good (North America only) phone number 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 { | |
if (textField == self.myPhoneTextField) { | |
NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string]; | |
BOOL deleting = [newText length] < [textField.text length]; | |
NSString *stripppedNumber = [newText stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [newText length])]; | |
NSUInteger digits = [stripppedNumber length]; | |
if (digits > 10) | |
stripppedNumber = [stripppedNumber substringToIndex:10]; | |
UITextRange *selectedRange = [textField selectedTextRange]; | |
NSInteger oldLength = [textField.text length]; | |
if (digits == 0) | |
textField.text = @""; | |
else if (digits < 3 || (digits == 3 && deleting)) | |
textField.text = [NSString stringWithFormat:@"(%@", stripppedNumber]; | |
else if (digits < 6 || (digits == 6 && deleting)) | |
textField.text = [NSString stringWithFormat:@"(%@) %@", [stripppedNumber substringToIndex:3], [stripppedNumber substringFromIndex:3]]; | |
else | |
textField.text = [NSString stringWithFormat:@"(%@) %@-%@", [stripppedNumber substringToIndex:3], [stripppedNumber substringWithRange:NSMakeRange(3, 3)], [stripppedNumber substringFromIndex:6]]; | |
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:[textField.text length] - oldLength + range.length]; | |
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:newPosition]; | |
[textField setSelectedTextRange:newRange]; | |
return NO; | |
} | |
return YES; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment