iphone - determine if touch occurred in subview of a uiview
Asked Answered
F

4

9

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.

Farfetched answered 9/9, 2010 at 19:39 Comment(0)
E
12

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);
    }
}
Elissaelita answered 13/9, 2011 at 12:45 Comment(0)
L
2
-(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])
}
Lapides answered 9/9, 2010 at 19:59 Comment(2)
But this method is a subclass of UIView, so this crashes:Farfetched
sorry, i guess I need to add an answer to explain - see belowFarfetched
D
1

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;
}
Doublespace answered 9/4, 2013 at 9:11 Comment(0)
P
0

Swift version:

  var yourSubview: UIView!

  override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    return subviewAtPoint(point) == yourSubview 
  }

  private func subviewAtPoint(point: CGPoint) -> UIView? {
    for subview in subviews {
      let view = subview.hitTest(point, withEvent: nil)
      if view != nil {
        return view
      }
    }
    return nil
  }
Profanity answered 28/3, 2016 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.