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


当前回答

老实说,我对这里提出的任何解决方案都不感兴趣。我确实发现了一种使用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]; }

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

其他回答

您可以使用[view ended:YES]强制当前正在编辑的视图放弃其第一响应器状态。这样就隐藏了键盘。

与-[UIResponder resignFirstResponder]不同,-[UIView enditing:]将通过子视图搜索当前的第一响应器。所以你可以把它发送到顶层视图(比如self)。UIViewController中的view)它会做正确的事情。

(这个答案之前包含了几个其他的解决方案,它们也可以工作,但比必要的更复杂。为了避免混淆,我把它们去掉了。)

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

[self.view endEditing:YES];

or

[self.textField resignFirstResponder];

比Meagar的回答更简单

覆盖touchesBegan: withEvent:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [textField resignFirstResponder];`
}

当你在背景中触摸任何地方时,这将使键盘消失。

在你的视图控制器的头文件中添加<UITextFieldDelegate>到你的控制器接口的定义中,以便它符合UITextField委托协议…

@interface someViewController : UIViewController <UITextFieldDelegate>

... 在控制器的实现文件(.m)中添加以下方法,或者如果你已经有一个viewDidLoad方法,则在其中添加代码…

- (void)viewDidLoad
{
    // Do any additional setup after loading the view, typically from a nib.
    self.yourTextBox.delegate = self;
}

... 然后,链接你的文本框到你的实际文本字段

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField 
{
    if (theTextField == yourTextBox) {
        [theTextField resignFirstResponder];
    }
    return YES;
}

关于如何在iOS中当用户触摸屏幕上UITextField或键盘之外的任何地方时取消键盘的快速提示。考虑到iOS键盘所占用的空间,为用户提供一种简单直观的方式来消除键盘是有意义的。

这是一个链接