Skip to content

Instantly share code, notes, and snippets.

@benvium
Created November 29, 2012 14:12
Show Gist options
  • Select an option

  • Save benvium/4169334 to your computer and use it in GitHub Desktop.

Select an option

Save benvium/4169334 to your computer and use it in GitHub Desktop.
Auto-tab between UITextFields with maximum numbers of chars (e.g. for a telephone number 000-222-3333)
// In IB, set up your UITextFields with tags 1,2,3
// Set the 'delegate' for each UITextField to be the main ViewController
// Set your ViewController to implement UITextFieldDelegate
// Add function below to your ViewController - use the values in the switch statement to limit the number of chars allowed in each UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
int maxSize;
switch (textField.tag) {
case 1:
maxSize = 3;
break;
case 2:
maxSize = 4;
break;
case 3:
maxSize = 2;
break;
}
// allow delete and tab to previous textfield if field is empty.
if ([string length] == 0) {
// tab to previous...
int64_t delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
if ([textField.text length] == 0) {
[[self.view viewWithTag:textField.tag-1] becomeFirstResponder];
}
});
return YES;
}
// if we're about to add last allowed char, tab to next
if ( [textField.text length] == maxSize - 1) {
int64_t delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
UIView* next = [self.view viewWithTag:textField.tag+1];
// If there isn't a next one, close the keyboard.
if (!next || ![next isKindOfClass:[UITextField class]]) {
[textField resignFirstResponder];
} else {
[next becomeFirstResponder];
}
});
return YES;
}
// add no more chars if at max size
if ( ([textField.text length] >= maxSize) ) {
return NO;
}
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment