UITextField, automatically move to next after 1 character

后端 未结 6 623

Scenario: I have 4 UITextFields that only accept 1 character. Easy.

Problem: After I enter the 1 character, I want the next TextField to become active automatically with

6条回答
  •  离开以前
    2021-01-31 12:24

    I know this is a very old question, but here's my approach for allowing a single numeric value only across four UITextFields, and automatically 'tabbing' to the next one (pin1-pin4 each represents a PIN number digit lol, and are retained as properties):

    -(BOOL)textFieldShouldReturn:(UITextField*)textField;
    {
        if (textField == pin1)
        {
            [pin2 becomeFirstResponder];
        }
        else if (textField == pin2)
        {
            [pin3 becomeFirstResponder];
        }
        else if (textField == pin3)
        {
            [pin4 becomeFirstResponder];
        }
    
        return NO;
    }
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        // This allows numeric text only, but also backspace for deletes
        if (string.length > 0 && ![[NSScanner scannerWithString:string] scanInt:NULL])
            return NO;
    
        NSUInteger oldLength = [textField.text length];
        NSUInteger replacementLength = [string length];
        NSUInteger rangeLength = range.length;
    
        NSUInteger newLength = oldLength - rangeLength + replacementLength;
    
        // This 'tabs' to next field when entering digits
        if (newLength == 1) {
            if (textField == pin1)
            {
                [self performSelector:@selector(setNextResponder:) withObject:pin2 afterDelay:0.2];
            }
            else if (textField == pin2)
            {
                [self performSelector:@selector(setNextResponder:) withObject:pin3 afterDelay:0.2];
            }
            else if (textField == pin3)
            {
                [self performSelector:@selector(setNextResponder:) withObject:pin4 afterDelay:0.2];
            }
        }
        //this goes to previous field as you backspace through them, so you don't have to tap into them individually
        else if (oldLength > 0 && newLength == 0) {
            if (textField == pin4)
            {
                [self performSelector:@selector(setNextResponder:) withObject:pin3 afterDelay:0.1];
            }
            else if (textField == pin3)
            {
                [self performSelector:@selector(setNextResponder:) withObject:pin2 afterDelay:0.1];
            }
            else if (textField == pin2)
            {
                [self performSelector:@selector(setNextResponder:) withObject:pin1 afterDelay:0.1];
            }
        }
    
        return newLength <= 1;
    }
    
    - (void)setNextResponder:(UITextField *)nextResponder
    {
        [nextResponder becomeFirstResponder];
    }
    

提交回复
热议问题