我正在使用类似 this solution 的手势识别器如果用户在我的文本字段之一之外点击,则隐藏键盘。在我的例子中,我使用的是 ScrollView ,顶部有一些文本字段。还实现了一些自动滚动功能(这就是我使用 ScrollView 的原因)。
如果用户点击键盘外部,我可以隐藏键盘。这是工作。我还启用了文本字段的清除按钮(右侧的 x 按钮)。如果用户点击它,键盘将被隐藏,但文本字段的内容不会被清除。通常我希望在这种情况下内容被清除并且键盘不会被关闭。 Patrick也发现了这个问题.
我试图获取 UITapGestureRecognizer
的点击对象,但这似乎是 UIScrollView
。我怎样才能让清除按钮和自动键盘隐藏功能起作用?
适用于所有文本字段的通用解决方案会很好。为了完成我的问题,我添加了我的代码(在 C# 中):
UITapGestureRecognizer tapGesture = new UITapGestureRecognizer ();
tapGesture.CancelsTouchesInView = false;
tapGesture.AddTarget (() => HandleSingleTap (tapGesture));
this.scrollView.AddGestureRecognizer (tapGesture);
private void HandleSingleTap(UITapGestureRecognizer recognizer){
this.scrollView.EndEditing(true);
}
您当然可以为 Objective-C 提供您的解决方案。
最佳答案
您应该能够从 gestureRecognizer 转换点击位置,以便您可以查看文本字段是否被点击
我没有验证它,但像这样的东西应该可以工作:
- (void)handleTap:(UITapGestureRecognizer *)sender {
BOOL tappedTextField = NO;
UIScrollView *scrollView = (UIScrollView *)sender.view;
for (UITextField *textField in self.textFields) {
CGRect textFieldBounds = textField.bounds;
CGRect textFieldFrameInScrollView = [textField convertRect:textFieldBounds toView:scrollView];
CGPoint tapLocationInScrollView = [sender locationInView:scrollView];
if (CGRectContainsPoint(textFieldFrameInScrollView, tapLocationInScrollView)) {
tappedTextField = YES;
break;
}
// Might work as well instead of the above code:
CGPoint tapLocationInTextField = [sender locationInView:textField];
if (CGRectContainsPoint(textField.bounds, tapLocationInTextField)) {
tappedTextField = YES;
break;
}
}
if (!tappedTextField) {
// handle tap
}
}
关于ios - 如果同时使用自动键盘隐藏,则文本字段的清除按钮 (x) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482415/