Skip to content

Instantly share code, notes, and snippets.

@stigi
Created May 11, 2011 10:27
Show Gist options
  • Save stigi/966250 to your computer and use it in GitHub Desktop.
Save stigi/966250 to your computer and use it in GitHub Desktop.
Conditional hit test
// using hit test
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
BOOL didHitLink = ([self linkAtPoint:point] != nil);
if (self.onlyCatchTouchesOnLinks && !didHitLink) {
return nil; // not catch the touch if it didn't hit a link
}
// never return self. always return the result of [super hitTest..].
// this takes userInteraction state, enabled, alpha values etc. into account
return [super hitTest:point withEvent:event];
}
// using pointInside
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
BOOL didHitLink = ([self linkAtPoint:point] != nil);
if (self.onlyCatchTouchesOnLinks && !didHitLink) {
return NO;
}
return [super pointInside:point withEvent:event];
}
@stigi
Copy link
Author

stigi commented May 11, 2011

we're currently discussing if it's smarter to use -pointInside.
waiting for comments :)

@stigi
Copy link
Author

stigi commented May 11, 2011

in offline discussion with @Gernot & @toto we came to the point that the key situation here is the following:
if the view contains a subview (i.e. a button) than this subview should be handling the touches if it is hit. so the right implementation would be https://gist.github.com/966295

@Gernot
Copy link

Gernot commented May 11, 2011

I think -hitTest is the way to go. We want an exception for touch events, so we should use the touch-specific methotd. -pointInside, even though senible for events is more general purpose. Also it does other nice stuff like consider transparency, hidden, etc.

However we should take into account that we might hit a subview by checking if the super method returns self:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

    UIView *returnValue = [super hitTest:point withEvent:event];

    if (self.onlyCatchTouchesOnLinks &&
        returnValue == self &&
        [self linkAtPoint:point] != nil)
    {
        returnValue = nil;
    }

    return returnValue;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment