Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a UIView that captures taps, but is transparent to all other gestures

I want to achieve the following.

Scenario: The iOS keyboard is on-screen while the user is typing into a particular text field. The user can tap anywhere outside of the keyboard and text field to dismiss the keyboard (without activating any buttons which are visible). Also, the user can drag outside of the keyboard and observe the normal drag behavior on some arrangement of scrollable views.

Conceptually, I’m placing a “cover” UIView over most of the screen which behaves such that:

  1. If the user taps on the cover, then I capture that tap (so that I can, e.g., dismiss the keyboard). This is easy to achieve by intercepting touch events in a UIView subclass or using a tap gesture recognizer.

  2. If the user drags on the cover, then the cover ignores or forwards these touches; these are received by the layers underneath just as they would have been without a cover.

So: the user should be able to scroll content underneath the cover, but not tap content underneath the cover. A tap “outside” of the keyboard and text field should dismiss the keyboard (and cover), but should not activate anything.

How can I achieve this?

like image 407
mjh Avatar asked Nov 16 '12 08:11

mjh


1 Answers

Add the tap gesture the usual way:

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
[self.view addGestureRecognizer:tapGesture];

But what you may be looking for is this :

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    {    
        return YES;
    }

Documentation says : This method is called when recognition of a gesture by either gestureRecognizer or otherGestureRecognizer would block the other gesture recognizer from recognizing its gesture. (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIGestureRecognizerDelegate_Protocol/index.html#//apple_ref/occ/intf/UIGestureRecognizerDelegate)

This way, you may be sure it's totally transparent, and also that nothing will prevent your recognizer from being called.

like image 145
cwehrung Avatar answered Sep 20 '22 15:09

cwehrung