iphone - 确定是否在uiview的子视图中发生了触摸

时间:2010-09-09 19:39:10

标签: iphone events uiview touch subview

在UIView的子类中我有:

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

       return NO;
    }

我可以在if语句中添加什么内容?我想检测子视图中是否发生了触摸,无论它是否位于UIView的框架内。

4 个答案:

答案 0 :(得分:12)

试试:

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

如果您想要在实现此方法的视图内部返回YES,请使用以下代码:(如果您要将手势识别器添加到位于容器边界之外的子视图中)

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if ([super pointInside:point withEvent:event])
    {
        return YES;
    }
    else
    {
        return CGRectContainsPoint(subview.frame, point);
    }
}

答案 1 :(得分:2)

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

方法 - (UIView *)hitTest:(CGPoint)指向withEvent:(UIEvent *)事件返回包含指定点的视图层次结构(包括其自身)中接收器的最远后代。我在那里做的是返回最远视图与子视图的比较结果。如果您的子视图也有子视图,则这可能对您不起作用。那么在这种情况下你想要做的是:

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

答案 2 :(得分:1)

尝试这个:

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

答案 3 :(得分:0)

Swift版本:

  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
  }