views:

181

answers:

2

In a subclass of UIView I have this:

    -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
    {
       if(touch occurred in a subview){
         return YES;
       }

       return NO;
    }

What can I put in the if statement? I want to detect if a touch occurred in a subview, regardless of whether or not it lies within the frame of the UIView.

+1  A: 
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
   return ([self hitTest:point withEvent:nil] == yourSubclass)
}

The method - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point. What I did there is return the result of the comparison of the furthest view down with your subview. If your subview also has subviews this may not work for you. So what you would want to do in that case is:

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
   return ([[self hitTest:point withEvent:nil] isDescendantOfView:yourSubclass])
}
Brad Smith
But this method is a subclass of UIView, so this crashes:
sol
sorry, i guess I need to add an answer to explain - see below
sol
A: 

But this method is in a subclass of UIView, so this crashes:

return ([[self hitTest:point withEvent:nil] isDescendantOfView:self])

Presumably because of infinite recursion.

I tried this:

NSSet* touches = [event allTouches];
UITouch* touch = [touches anyObject];

return ([touch.view isDescendantOfView:self] || touch.view == self);

But it always returns NO

sol
This did work for me in a UIView subclass:-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if ([touch.view isDescendantOfView:mySubView]) { NSLog(@"YUP"); } else { NSLog(@"NOPE"); }}
Brad Smith
this does not detect touches outside the view's frame though - that's the most important part I'm looking for.
sol