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


当前回答

从UITableView和UIScrollView中取消键盘的最好方法是:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag

其他回答

从UITableView和UIScrollView中取消键盘的最好方法是:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag

这是一个解决方案,使键盘离开时,点击返回在任何文本字段,通过添加代码在一个地方(所以不必为每个文本字段添加一个处理程序):


考虑一下这个场景:

我有一个带有两个文本字段(用户名和密码)的视图控制器。 并且视图控制器实现UITextFieldDelegate协议

我在viewDidLoad中这样做

- (void)viewDidLoad 
{
    [super viewDidLoad];

    username.delegate = self;
    password.delegate = self;
}

而视图控制器实现了可选方法as

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

不管你在哪个文本域,只要我按下回车键,它就会消失!

在你的情况下,同样的工作,只要你设置所有的文本字段的委托自我和实现textFieldShouldReturn

我最近需要使用的一个稍微健壮一点的方法:

- (void) dismissKeyboard {
    NSArray *windows = [UIApplication sharedApplication].windows;

    for(UIWindow *window in windows) [window endEditing:true];

    //  Or if you're only working with one UIWindow:

    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

我发现其他一些“全局”方法不起作用(例如,UIWebView和WKWebView拒绝辞职)。

你必须使用其中一种方法,

[self.view endEditing:YES];

or

[self.textField resignFirstResponder];

老实说,我对这里提出的任何解决方案都不感兴趣。我确实发现了一种使用TapGestureRecognizer的好方法,我认为它解决了问题的核心:当你点击键盘以外的任何东西时,忽略键盘。

In viewDidLoad, register to receive keyboard notifications and create a UITapGestureRecognizer: NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil]; [nc addObserver:self selector:@selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object:nil]; tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)]; Add the keyboard show/hide responders. There you add and remove the TapGestureRecognizer to the UIView that should dismiss the keyboard when tapped. Note: You do not have to add it to all of the sub-views or controls. -(void) keyboardWillShow:(NSNotification *) note { [self.view addGestureRecognizer:tapRecognizer]; } -(void) keyboardWillHide:(NSNotification *) note { [self.view removeGestureRecognizer:tapRecognizer]; } The TapGestureRecognizer will call your function when it gets a tap and you can dismiss the keyboard like this: -(void)didTapAnywhere: (UITapGestureRecognizer*) recognizer { [textField resignFirstResponder]; }

这个解决方案的优点是它只过滤轻敲,而不是滑动。因此,如果你在键盘上方有滚动内容,滑动仍然会滚动并显示键盘。通过在键盘消失后移除手势识别器,未来在视图上的点击将被正常处理。