【问题标题】:Clear button (x) of textfield not working if auto keyboard hiding is used at the same time如果同时使用自动键盘隐藏,则文本字段的清除按钮 (x) 不起作用
【发布时间】:2014-12-15 10:52:46
【问题描述】:

如果用户在我的一个文本字段之外点击,我正在使用像 this solution 这样的手势识别器来隐藏键盘。就我而言,我正在使用顶部带有一些文本字段的滚动视图。还实现了一些自动滚动功能(这就是我使用滚动视图的原因)。

如果用户在键盘之外点击,我可以隐藏键盘。这是有效的。我还启用了文本字段的清除按钮(右侧的 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 提供解决方案。

【问题讨论】:

    标签: ios uiscrollview uitextfield uitapgesturerecognizer


    【解决方案1】:

    你应该能够从gestureRecognizer转换点击位置,这样你就可以看到textField是否被点击了

    我没有验证它,但这样的东西应该可以工作:

    - (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
        }
    }
    

    【讨论】:

    • 什么是self.textFields?它是一个包含对我所有文本字段的引用的数组吗?
    • 是的,我假设你有类似的东西来存储你的文本字段。
    猜你喜欢
    • 2012-07-05
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多