Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone - determine if touch occurred in subview of a uiview

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.

like image 382
sol Avatar asked Sep 09 '10 19:09

sol


3 Answers

Try that:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    return CGRectContainsPoint(subview.frame, point);
}

If you want to return YES if the touch is inside the view where you implement this method, use this code: (in case you want to add gesture recognizers to a subview that is located outside the container's bounds)

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if ([super pointInside:point withEvent:event])
    {
        return YES;
    }
    else
    {
        return CGRectContainsPoint(subview.frame, point);
    }
}
like image 146
Christian Schnorr Avatar answered Oct 24 '22 01:10

Christian Schnorr


-(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])
}
like image 34
Brad The App Guy Avatar answered Oct 24 '22 02:10

Brad The App Guy


TRY THIS:

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
   NSSet *touches = [event allTouches];
   UITouch *touch = [touches anyObject];
   if([touch.view isKindOfClass:[self class]]) {
   return YES;
   }
   return NO;
}
like image 37
Abhishek Bedi Avatar answered Oct 24 '22 02:10

Abhishek Bedi