如何不允许圆形UIView识别它的圆形边界之外的触摸?

时间:2015-01-26 04:11:05

标签: ios swift uiview uipangesturerecognizer

我有两个视图叠加在一起。我们假设视图B堆叠在较大视图A的顶部。视图B是圆形的,不应接受圆形外部的触摸,而是较大的视图A应接受触摸。

我已经尝试覆盖视图B的自定义PanGesture识别器的touchesBegan方法,以检查它是否在圆形路径中,然后在识别器上调用取消触摸,如下所示:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    let touch = touches.anyObject() as UITouch
    let location = touch.locationInView(self.view)
    let isInPath = self.path.containsPoint(location)

    if(isInPath){
        super.touchesBegan(touches, withEvent: event)
        self.rotation = rotationForLocation(location)
    }else{
        // touch started outside of path so cancel touch
        super.cancelsTouchesInView = true
        super.touchesCancelled(touches, withEvent: event)
    }
}

它阻止视图B接受圆形路径外的触摸,但视图A不接受触摸。任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:1)

您可以添加两个手势识别器,其中一个手势识别器将指定一个gestureRecognizerShouldBegin方法的委托,只有在圈内时才会启动手势。然后,只有当圆形手势失败时,才能使非圆形手势成功。

// add square view

let subview = UIView(frame: frame)
subview.backgroundColor = UIColor.lightGrayColor()
subview.userInteractionEnabled = true
view.addSubview(subview)

// add circular shapelayer (so I can see the circle)

let circularShapeLayer = CAShapeLayer()
circularShapeLayer.frame = subview.bounds
circularShapeLayer.path = UIBezierPath(ovalInRect: subview.bounds).CGPath
circularShapeLayer.fillColor = UIColor.darkGrayColor().CGColor
subview.layer.addSublayer(circularShapeLayer)

// add gesture that will use delegate method `gestureRecognizerShouldBegin` to determine if you started in the circle

let circlePanGesture = UIPanGestureRecognizer(target: self, action: "handleCircularPan:")
circlePanGesture.delegate = self
subview.addGestureRecognizer(circlePanGesture)

// add a gesture recognizer that will only be recognized if the prior gesture recognizer fails

let squarePanGesture = UIPanGestureRecognizer(target: self, action: "handleSquarePan:")
squarePanGesture.requireGestureRecognizerToFail(circlePanGesture)
subview.addGestureRecognizer(squarePanGesture)

委托方法可能如下所示:

func gestureRecognizerShouldBegin(gesture: UIGestureRecognizer) -> Bool {
    let center = CGPoint(x: gesture.view!.bounds.size.width / 2.0, y: gesture.view!.bounds.size.height / 2.0)
    let location = gesture.locationInView(gesture.view)
    let distance = hypot(center.x - location.x, center.y - location.y)
    return distance < (gesture.view!.bounds.size.width / 2.0)
}

注意,我正在将这两个手势添加到同一个子视图中(因为如果我有重叠的视图,两者都有userInteractionEnabled,只有获得手势时才能显示最高的视图。)

答案 1 :(得分:0)

请勿取消触摸,而是将它们转发给A对象。