代码之家  ›  专栏  ›  技术社区  ›  RUON

如何仅允许在场景中的特定区域进行触摸?

  •  0
  • RUON  · 技术社区  · 9 年前

    我想将触摸设置为仅在屏幕的一部分,我已尝试在屏幕的不允许触摸的部分添加节点层,并禁用用户交互

    _mainLayer.userInteractionEnabled = NO;
    

    但它不起作用,不知道怎么做?

    2 回复  |  直到 9 年前
        1
  •  1
  •   0x141E    9 年前

    以下是如何将触摸事件限制在特定区域的示例:

    敏捷的

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        for touch in (touches as! Set<UITouch>) {
            let location = touch.locationInNode(self)
    
            switch (location) {
            case let point where CGRectContainsPoint(rect, point):
                // Touch is inside of a rect
                ...
            case let point where CGPathContainsPoint(path, nil, point, false):
                // Touch is inside of an arbitrary shape
                ...
            default:
                // Ignore all other touches
                break
            }
        }
    }
    

    目标-C

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        for (UITouch *touch in touches) {
            CGPoint location = [touch locationInNode:self];
    
            if (CGRectContainsPoint(rect, location)) {
    
            }
            else if (CGPathContainsPoint(path, nil, location, false)) {
    
            }
        }
    }
    
        2
  •  0
  •   Aurast    9 年前

    我没有足够的评论空间来深入讨论,所以这只是一个准答案。

    在您的评论截图中,您似乎不希望在视图底部200像素高的区域中的任何地方识别触摸。

    您可以让视图采用UIGestureRecognizerDelegate协议并实现shouldReceiveTouch方法。尝试这样实现该方法(我已经有一段时间没有使用Objective-C了,如果任何语法都不正确,请原谅我):

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch 
    {
        CGPoint touchPointInView = [touch locationInView:self];
    
        if (touchPointInView.y >= CGRectGetMaxY(self.bounds) - 200)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    

    不要忘记设置手势识别器的代理(在视图的构造函数中往往是一个好地方):

    gestureRecognizer.delegate = self;