UIGestureRecognizer 只为 subView 添加,但它也适用于 parentView?

UIGestureRecognizer is only added for subView but it is also working on parentView?

这是我的代码:

[super viewDidLoad];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
    [self.colorView setUserInteractionEnabled:YES];
    [self.colorView addGestureRecognizer:tapGesture];

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    UITouch *touch = [[event allTouches] anyObject];
    touchPoint = [touch locationInView:self.colorView];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(touchPoint.x,touchPoint.y)];
    [path addLineToPoint:CGPointMake(startingPoint.x,startingPoint.y)];
    startingPoint=touchPoint;
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
    shapeLayer.lineWidth = 3.0;
    shapeLayer.fillColor = [[UIColor redColor] CGColor];
    [self.colorView.layer addSublayer:shapeLayer];

    NSLog(@"Touch moving point =x : %f Touch moving point =y : %f", touchPoint.x, touchPoint.y);



}

所以它只能在 colorView 上工作,但发生的是 ,触摸也在 self.view 内部工作,如何解决这个问题。

Views 跟踪在它们内部开始的触摸,即使触摸超出了它们的边界(这就是为什么你可以按住一个按钮,拖出它,当你在一定距离内时它仍然会被选中)

您可以使用 CGRectContainsPoint 仅在视图内添加一个点。

您可以添加:

 self.colorView.clipsToBounds = YES;

它将解决您的问题。

A Boolean value that determines whether subviews are confined to the bounds of the view.

Declaration OBJECTIVE-C @property(nonatomic) BOOL clipsToBounds Discussion Setting this value to YES causes subviews to be clipped to the bounds of the receiver. If set to NO, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is NO.

Availability Available in iOS 2.0 and later. Link: Reference

所以因为它不是。因此交互将扩展到超级视图。当您设置为 YES 时。它只适用于您的子视图。