简体   繁体   中英

Clear button (x) of textfield not working if auto keyboard hiding is used at the same time

I'm using a gesture recognizer like this solution to hide the keyboard if the user taps outside of one of my textfields. In my case I'm using a scroll view with some textfields on top. There is also some auto-scroll feature implemented (that's why I'm using the scroll view).

I can hide the keyboard if the user taps outside of it. This is working. I have also enabled the clear button (x button on the right) of the textfield. If the user taps on it the keyboard is hidden, but the content of the textfield is not cleared. Normally I would expect that the content is cleared and the keyboard is not dismissed in this case. This problem was also found by Patrick .

I tried to get the tapped object of the UITapGestureRecognizer , but this seems to be the UIScrollView . How can I get the clear button and the auto keyboard hiding feature working?

A generic solution would be nice that would work for all textfields. To complete my question I add my code (which is in 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);
}

You can of course provide your solutions for Objective-C.

you should be able to convert the tap location from the gestureRecognizer so you can see if the textField was tapped

I didn't verify it but something like this should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM