Created
November 29, 2012 14:12
-
-
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)
This file contains hidden or 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
| // 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