iphone - determine if touch occurred in subview of a uiview

匆匆过客 提交于 2019-12-04 19:22:01

问题


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:


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



回答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])
}



回答3:


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



回答4:


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
  }


来源:https://stackoverflow.com/questions/3679978/iphone-determine-if-touch-occurred-in-subview-of-a-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!