我可以使用代码按 return 键吗?

Can I press the return key using code?

我有一个 uitextfield,我计算字符数。这个想法是,当计数达到四时,它应该继续到下一个文本字段。问题是,虽然计数器告诉我该字段确实包含四个字符,但该字段只显示三个字符。当我手动按下 return 键时它会起作用,但我不需要用户必须这样做。这是我的代码。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSInteger textLength = 0;
    textLength = [textField.text length] + [string length] - range.length;
    NSLog(@"Length: %ld", (long)textLength);
    NSLog(@"tag: %ld", (long)textField.tag);
    if (textField.tag == 1 || textField.tag == 2) {
        if (textLength == 4) {
            NSLog(@"doneeee");
            NSLog(@"testfield: %@", textField.text);
           }
    }

  if (textField.tag == 3) {
            NSLog(@"we're here");
            if (textLength == 6) {
                NSLog(@"Zip is done");
                [self checkTheTextField:textField];
        }
    }


    return YES;
}

当文本长度为 4

时尝试 resignFirstResponderbecomeFirstResponder

正如评论中所指出的,您在 NSLog 语句中只看到 3 个字符被打印出来的原因是因为更改尚未应用到 textField.text 直到方法returns YES。为了让应用程序在达到所需长度时自动 select 下一个文本字段,您只需在下一个文本字段上调用 ​​becomeFirstResponder。例如:

if(textLength == 4)
{
    NSLog(@"doneeee");

    // Here's how you can output the field's text, assuming you will return YES
    NSLog(@"testfield: %@", [textField.text stringByReplacingCharactersInRange:range withString:string];

    // Here's how you make the next field active
    [nextTextFieldOutlet becomeFirstResponder];  // Or whatever you field is called.
}

return YES;

作为旁注,如果字段的长度 大于 ,您可能希望通过此方法将一些逻辑放入 return NO特定字段所需的长度。例如,如果您的邮政编码字段最多只需要 6 个,请在这种情况下检查 fieldLength > 6 和 return NO。这样,如果有人试图粘贴一个长字符串,它就会拒绝它。

作为另一种选择,当长度达到 4 时,您可以直接设置 textField.text,将下一个文本字段设置为第一响应者,并且 return NO.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (textField.tag == 1 || textField.tag == 2) {
        if (text.length == 4) {
            textField.text = text;
            [yourNewTextField becomeFirstResponder];
            return NO;
        }
    }

    // ...

    return YES;
}