我有相当多的控件分散在我的表格中的许多表格单元格中,我想知道是否有一种更简单的方法来消除键盘,而不必循环遍历所有的控件并将它们全部辞职为第一响应器。我想问题是…我如何得到当前的第一个响应器的键盘?


当前回答

添加一个点击手势识别器到您的视图。并定义为ibaction

你的。m文件就像

    - (IBAction)hideKeyboardGesture:(id)sender {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in windows) [window endEditing:true];
    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

这对我很有效

其他回答

Try:

[self.view endEditing:YES];

要在键盘弹出后关闭键盘,有两种情况,

当UITextField在UIScrollView中 当UITextField在UIScrollView之外时

2.当UITextField在UIScrollView之外时 重写UIViewController子类中的方法

你还必须为所有UITextView添加委托

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

在滚动视图中,点击外部不会触发任何事件,所以在这种情况下使用点击手势识别器, 拖拽滚动视图的UITapGesture并为其创建IBAction。

要创建一个IBAction,按ctrl+单击UITapGesture并将其拖到视图控制器的.h文件中。

这里我将tappedEvent命名为我的动作名

- (IBAction)tappedEvent:(id)sender {
      [self.view endEditing:YES];  }

以上所提供的信息来自以下链接,如果您不理解以上数据,请参阅更多信息或与我联系。

http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/

更好的方法是让某些东西“窃取”第一响应者的地位。

因为UIApplication是UIResponder的子类,你可以尝试:

[[UIApplication sharedApplication] becomeFirstResponder]
[[UIApplication sharedApplication] resignFirstResponder]

如果做不到这一点,创建一个新的UITextField与一个零大小的框架,将它添加到一个视图的某处,并做一些类似的事情(成为后跟辞职)。

最简单的方法是调用方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    if(![txtfld resignFirstResponder])
    {
        [txtfld resignFirstResponder];
    }
    else
    {

    }
    [super touchesBegan:touches withEvent:event];
}

@Nicholas Riley &@Kendall Helmstetter Geln & @cannyboy:

绝对的辉煌!

谢谢你!

考虑到你和其他人在这篇文章中的建议,以下是我所做的:

使用时的样子:

[[self appDelegate]解聘键盘];(注意:我添加了appDelegate作为NSObject的补充,所以我可以在任何地方使用任何东西)

引擎盖下的样子:

- (void)dismissKeyboard 
{
    UITextField *tempTextField = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
    tempTextField.enabled = NO;
    [myRootViewController.view addSubview:tempTextField];
    [tempTextField becomeFirstResponder];
    [tempTextField resignFirstResponder];
    [tempTextField removeFromSuperview];
}

EDIT

修正我的回答包括tempTextField。enabled = NO;。禁用文本字段将阻止UIKeyboardWillShowNotification和UIKeyboardWillHideNotification键盘通知发送,如果你在整个应用程序中依赖这些通知。