在Swift中单击CAShapeLayer时检测触摸

时间:2016-06-04 16:17:46

标签: ios swift cashapelayer

我制作了一个可以在红色圆圈路径中拖动的蓝色球: enter image description here

拖动功能很棒,但是!它可以在我点击屏幕的任何地方使用,我想在点击蓝色球时将其​​拖动

到目前为止,这是我的代码:

override func viewDidLoad() {
        super.viewDidLoad()
circlePath2 = UIBezierPath(arcCenter: CGPoint(x: earthX,y: earthY), radius: CGFloat(10), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
        shapeLayer2.path = circlePath2.CGPath
        shapeLayer2.fillColor = UIColor.blueColor().CGColor
        shapeLayer2.strokeColor = UIColor.clearColor().CGColor
        shapeLayer2.lineWidth = 7
        view.layer.addSublayer(shapeLayer2)

        let dragBall = UIPanGestureRecognizer(target: self, action:#selector(ViewController.dragBall(_:)))
        view.addGestureRecognizer(dragBall)
}
@IBAction func dragBall(recognizer: UIPanGestureRecognizer) {
            let point = recognizer.locationInView(self.view)
            let earthX = Double(point.x)
            let earthY = Double(point.y)
            let midViewXDouble = Double(midViewX)
            let midViewYDouble = Double(midViewY)
            let angleX = (earthX - midViewXDouble)
            let angleY = (earthY - midViewYDouble)
            angle = atan2(angleY, angleX)
            let earthX2 = midViewXDouble + cos(angle)*100
            let earthY2 = midViewYDouble + sin(angle)*100
            circlePath2 = UIBezierPath(arcCenter: CGPoint(x: earthX2,y: earthY2), radius: CGFloat(10), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
            shapeLayer2.path = circlePath2.CGPath
}

我尝试将下面的代码添加到dragBall函数中,就像判断:(它检测用户是否完全触及蓝色球)

if ((point.x >= circlePath2.currentPoint.x - circlePath2.bounds.width/2) && (point.y <= circlePath2.currentPoint.y + circlePath2.bounds.height/2)) && ((point.y >= circlePath2.currentPoint.y - circlePath2.bounds.height/2) && (point.y <= circlePath2.currentPoint.y + circlePath2.bounds.height/2)){

它有效,但我只能在我的触摸不离开蓝球位置时拖动它,例如,如果我想在触摸他时才开始触球 - 我可以,但是当我拖动时继续移动他在屏幕的其他地方 - 我不能。

快捷方式:只有当我触摸它时才开始拖动球。当我的触摸在屏幕的任何地方时继续拖动。

1 个答案:

答案 0 :(得分:0)

dragBall功能中,阅读手势识别器的state属性。如果状态为UIGestureRecognizerStateBegan且触摸位于蓝色球内,则手势已正确启动,您可以允许后续手势影响球的位置,即使它们不在球内。

最佳方法可能是在创建符合delegate的手势时识别手势UIGestureRecognizerDelegate,然后实施gestureRecognizerShouldBegin:功能。在此功能中,如果触摸不在蓝色球内,则返回false。

以下是我与代表讨论的一个例子:

class MyClass: NSObject, UIGestureRecognizerDelegate {

  let ballView = UIView()

  func createRecognizer() {
      let recognizer = UIPanGestureRecognizer(target: self, action: #selector(MyClass.gestureRecognized(_:)))
      recognizer.delegate = self
      ballView.addGestureRecognizer(recognizer)
  }

  func gestureRecognized(recognizer: UIPanGestureRecognizer) {
      // update ball position
  }

  func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
      let location = gestureRecognizer.locationInView(ballView)
      return CGRectContainsPoint(ballView.bounds, location)
  }
}