平移手势无法正常工作

时间:2018-04-03 07:08:20

标签: ios swift uipangesturerecognizer

所以我正在创建一个带有网格的应用程序,当我点击时会创建一个节点。现在,我正在使用PanGesture将节点拖放到网格中的其他位置。现在,我希望我拖动的节点更大(因此用户更容易看到),然后在删除时返回其大小。所以我用“panGesture.state == begin”来实现一个扩大节点的动画。但是,此动画仅在节点开始移动时才开始,而不是在我触摸它时。根据Apple API,

A pan gesture recognizer enters the began state as soon as the 
**required amount of initial movement is achieved**

意味着在我开始拖动节点之前,我的节点不会更大。

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您可以同时使用长按和平移手势识别器。请参阅代码示例。

class ViewController: UIViewController, UIGestureRecognizerDelegate {
   var dragView: UIView!

   override func viewDidLoad() {
      super.viewDidLoad()

      self.dragView = UIView(frame: CGRect(x: 100.0, y: 100, width: 50.0, height: 50.0))
      self.dragView.backgroundColor = UIColor.red

      let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan))
      panRecognizer.delegate = self
      self.dragView.addGestureRecognizer(panRecognizer)

      let pressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(press))
      pressRecognizer.minimumPressDuration = 0.0 // IMPORTANT
      pressRecognizer.delegate = self
      self.dragView.addGestureRecognizer(pressRecognizer)

      self.view.addSubview(self.dragView)
   }

   @objc
   func press(gestureRecognizer: UILongPressGestureRecognizer) {
      switch gestureRecognizer.state {
         case .began:
            UIView.animate(withDuration: 0.1, animations: {
               self.dragView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
            })
         case .cancelled, .ended, .failed:
            UIView.animate(withDuration: 0.1, animations: {
               self.dragView.transform = CGAffineTransform.identity
            })
         default: break
      }
   }

   @objc
   func pan(gestureRecognizer: UIPanGestureRecognizer) {
      switch gestureRecognizer.state {
         case .changed:
            var center = self.dragView.center
            let translation = gestureRecognizer.translation(in: self.dragView)
            center.x += translation.x
            center.y += translation.y
            self.dragView.center = center
            gestureRecognizer.setTranslation(CGPoint.zero, in: self.dragView)
         default: break
      }
   }

   // MARK: UIGestureRecognizerDelegate
   @objc
   func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                          shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
      return true // IMPORTANT
   }
}

答案 1 :(得分:0)

在摇动手势中,.began表示开始移动而不是开始触摸。您必须重写func touchesBegan(_ touches:Set,带有事件:UIEvent?)函数以获得实际的触摸。