Skip to content

Instantly share code, notes, and snippets.

@mozeryansky
Created December 17, 2014 22:33
Show Gist options
  • Save mozeryansky/a7db31d28bf016555166 to your computer and use it in GitHub Desktop.
Save mozeryansky/a7db31d28bf016555166 to your computer and use it in GitHub Desktop.
This will maintain the text field to be formatted like a phone number, and have a placeholder as the user types in the number, i.e. "(12 ) - ". And all while maintaining the cursor position where the last number is typed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// new number
NSString *phoneNumber = [textField.text stringByReplacingCharactersInRange:range withString:string];
// strip non-numbers
NSString *rawPhoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
if(string.length == 0 && rawPhoneNumber.length == 3){
// delete again
phoneNumber = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(range.location-2, range.length) withString:string];
// strip non-numbers
rawPhoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
} else if(string.length == 0 && rawPhoneNumber.length == 6){
// delete again
phoneNumber = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(range.location-1, range.length) withString:string];
// strip non-numbers
rawPhoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
}
// pad and trim to 10 digits
phoneNumber = [[rawPhoneNumber stringByAppendingString:@" "] substringToIndex:10];
// add in format
phoneNumber = [NSString stringWithFormat:@"(%@) %@-%@",
[phoneNumber substringToIndex:3],
[phoneNumber substringWithRange:NSMakeRange(3, 3)],
[phoneNumber substringWithRange:NSMakeRange(6, 4)]];
[textField setText:phoneNumber];
NSInteger offset = rawPhoneNumber.length + 1;
if(rawPhoneNumber.length >= 3){
offset += 2;
}
if(rawPhoneNumber.length >= 6){
offset++;
}
// place cursor where use left off
UITextPosition *pos = [textField positionFromPosition:textField.beginningOfDocument
inDirection:UITextLayoutDirectionRight
offset:offset];
UITextRange *newRange = [textField textRangeFromPosition:pos toPosition:pos];
//select it to move cursor
textField.selectedTextRange = newRange;
return NO;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment