按下回车键时转到下一个文本字段

问题描述 投票:2回答:3

我编写了一个textFieldDone:方法,该方法应该在点击“返回”按钮时将光标移动到下一个文本字段。

- (IBAction)textFieldDone:(id)sender {
     [nextTextField becomeFirstResponder];
     NSLog(@"in : textFieldDone");
}

我已将第一个文本字段的“退出时结束结束”事件连接到文件的所有者,并选择了textFieldDone:方法。我还指定了文件的所有者作为文本字段的委托(因为我需要相应地向上/向下滚动视图,以便键盘不会隐藏文本字段)。

[当我在模拟器上运行该应用程序并点击返回按钮时,第一个文本字段退出了第一响应者,在日志中,我看到程序没有通过textFieldDone:方法,但是确实通过了textFieldDidEndEditing:方法。

我以前使用过这种方法,没有问题。

是因为文件的所有者是文本字段的委托人?

objective-c cocoa-touch ios5
3个回答
1
投票
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:txt1]) 
    {
        [txt2 becomeFirstResponder];
    }
    return true;    
}

3
投票

您需要写上

- (BOOL) textFieldShouldReturn:(UITextField*) textField

转到下一个文本字段。

示例代码:

-(BOOL) textFieldShouldReturn:(UITextField*) textField 
{
    if (textField == txt1)
    {
        [txt1 resignFirstResponder];
        [txt2 becomeFirstResponder];
    }
    if (textField == txt2)
    {
        [txt2 resignFirstResponder];
    }
    return YES;
}

不要忘记将委托UITextFieldDelegate添加到您的UITextfield。


1
投票

以上答案是正确的,但要使其更通用,应使用标记选项

UITextField *txt1;
txt1.tag=1;
UITextField *txt2;
txt2.tag=2;
UITextField *txt3;
txt3.tag=3;
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([[textField superview] viewWithTag:textField.tag+1])
        {
        [[[textField superview] viewWithTag:textField.tag+1] becomeFirstResponder];
        }
    else{  [textField resignFirstResponder];
    }
    return true;
}

注意:请勿将textField与标签0一起使用。因为默认情况下,所有subViews的标签都为0。

© www.soinside.com 2019 - 2024. All rights reserved.