开发者

iphone - determine if touch occurred in subview of a uiview

In a su开发者_如何转开发bclass 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.


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);
    }
}


-(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])
}


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;
}


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
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜