当 UITextField 失去焦点时隐藏键盘
我看过一些关于如何在 UITextField 失去焦点时关闭键盘的线程,但它对我不起作用,而且我不知道如何操作。以下代码中的“touchesBegan:withEvent:”永远不会被调用。为什么?
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
if ([self.textFieldOnFocus isFirstResponder] && [touch view] != self.textFieldOnFocus) {
[textFieldOnFocus resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}
PS:此代码已插入具有 UITableView 的视图控制器中。 UITextField 位于该表的一个单元格中。
所以,我的意见是:这个方法没有被调用,因为触摸发生在我的 ViewController 的 UITableView 上。所以,我认为,我应该对 UITableView 进行子类化,以使用我在其他线程上看到的方法,但它可能有更简单的方法。
请你帮助我好吗?多谢!
I've seen some threads about how to dismiss the Keyboard when a UITextField loses focus, but it did not work for me and I don't know how. The "touchesBegan:withEvent:" in the following code, never gets called. Why?
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
if ([self.textFieldOnFocus isFirstResponder] && [touch view] != self.textFieldOnFocus) {
[textFieldOnFocus resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}
P.S.: This code has been inserted in the view controller which has a UITableView. The UITextField is in a cell from this table.
So, my opinion is: this method is not being called, cause the touch occurs on the UITableView from my ViewController. So, I think, that to I should have to subclass the UITableView, to use this method as I have seen on other Threads, but it may have a easier way.
Could you please help me? Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保将
UITextField
的delegate
设置为 IB 中的First Responder
。我只是在屏幕上放置了一个自定义(不可见)UIButton
并设置了一个IBAction
来隐藏键盘。例如:将其连接到
UIButton
上。Make sure you set the
delegate
of theUITextField
toFirst Responder
in IB. And I just put a custom (invisible)UIButton
over the screen and set up anIBAction
to hide the keyboard. Ex:With that hooked up to a
UIButton
.这是我的解决方案,有点受到 SO 中几篇文章的启发:只需在视图上下文中处理点击手势,用户“显然”试图离开 UITextField 的焦点。
这是在 ViewController 中实现的。处理程序作为手势识别器添加到 View 属性设置器中的相应视图中:
处理程序也可以在 View 中定义。如果您不熟悉处理手势,请参阅 Apple 文档以及其他地方的大量示例。
我应该提到,您将需要一些额外的代码来确保其他控件获得点击,您需要一个实现 UIGestureRecognizerDelegate 协议和此方法的委托:
Here is my solution, somewhat inspired by several posts in SO: Simply handle the tap gesture in the context of the View, the user is 'obviously' trying to leave the focus of the UITextField.
This is implemented in the ViewController. The handler is added as a gesture recognizer to the appropriate View in the View property's setter:
The handler could be defined in the View as well. If you are unfamiliar with handling gestures, see Apple's docs are tons of samples elsewhere.
I should mention that you will need some additional code to make sure other controls get taps, you need a delegate that implements the UIGestureRecognizerDelegate protocol and this method: