resignFirstResponder仅在某些情况下成功隐藏键盘

时间:2013-04-03 13:22:57

标签: iphone cocoa-touch keyboard uitextfield

我正在使用resignFirstResponder来隐藏数字键盘,但它只在隐藏键盘时有效:我使用backgroundTap实现[textField resignFirstResponder];并在背景上点按键盘确实是隐藏的。我还在viewWillDisappear中添加了这一行,但它在某些时候也可以使用。当用户回到他来自的窗口时,键盘消失。但当他进入一个新窗口(而不是他来自的那个窗口)时,键盘不会消失。我使用方法isFirstResponder检查了调试,并且在两种情况下,文本字段确实不再是第一个响应者(尽管在其中一种情况下键盘一直显示,如上所述)。

viewWillDisappear的实施是这样的:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [textField resignFirstResponder];
    [self.view endEditing:YES];
}

我想在viewWillDisappear的情况下隐藏键盘,因为新窗口没有与此键盘相关的文本字段。它有完全不同的元素。

推送另一个视图的事件不是单击按钮,而是编辑文本字段的开始。我的视图中有三个文本字段,其中只有一个显示键盘。另外两个推动了另一个观点。这是textFieldDidBeginEditing的代码:

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField1.editing == YES)
    {
        [self performSegueWithIdentifier:@"goToView1" sender:self];
     }
    else if (textField2.editing == YES)
    {
        [self performSegueWithIdentifier:@"goToView2" sender:self];
    }

}

生成键盘的文本字段是textField3。

关于如何使键盘在两种情况下消失的一些想法?

2 个答案:

答案 0 :(得分:0)

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
     if (textField == textField1)
     {
         [self.view endEditing:YES]; 
         //else you can try with this also.
         [textField performSelector:@selector(resignFirstResponder)
                withObject:nil
                afterDelay:0];
         //
         [self performSegueWithIdentifier:@"goToView1" sender:self];
         return NO;
     }
     else if (textField == textField2)
     {
         [self.view endEditing:YES];
         [self performSegueWithIdentifier:@"goToView2" sender:self];
         return NO;
     }
    return YES;
}

答案 1 :(得分:0)

使用此代码检查是否存在任何文本字段并使用它来关闭键盘。根据您的需求进行调整。

for (id elem in self.view.subviews) {
    if ([elem isKindOfClass:[UITextField class]]) {
        [(UITextField *)elem resignFirstResponder];
    }
}