简体   繁体   中英

iOS/ObjC: “Fallback” tap gesture recognizer?

I have a UIViewController subclass whose view will generally contain some number of UIButtons and other interactive elements which may have one or more gesture recognizes attached to them.

What I'm trying to do is provide some visual feedback in the event that the user taps on a part of the screen that is not interactive. In other words: when the user taps the screen anywhere, if and only if no other control in the view responds to the touch event (including if it's, say, the start of a drag), then I want to fire off a method based on the location of the tap.

Is there a straightforward way to do this that would not require my attaching any additional logic to the interactive elements in the view, or that would at least allow me to attach such logic automatically by traversing the view hierarchy?

You can override the pointInside:withEvent: method of the container view and return NO if there is an interactive element under the tapped location, and return YES otherwise. The case where you return YES will correspond to tapping on an empty location.

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    // Perform some checks using the CGRectContainsPoint method
    // e.g. CGRectContainsPoint(oneOftheSubviews.frame, point)   
}

A good alternative is using the hitTest:withEvent: method as in the example below:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *hitView = [super hitTest:point withEvent:event];
    if (hitView != someView) return nil;
    return hitView;
}

[super hitTest:point withEvent:event] will return the deepest view in that view's hierarchy that was tapped.

So you can check the type of hitView , and if it corresponds to one of your interactive subviews, return it. If it is equal to self , then it means that there isn't a subview under the tapped location, which in your case means that the user tapped on an empty area. In that case you'll do whatever you want to do and then return nil .

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