将平移手势限制为一个方向

时间:2019-04-01 22:05:50

标签: swift gesture

只希望图像向上平移。

我尝试编辑x和y坐标。尝试根据翻译生成新的y变量,但不会更改。

@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer)     {
    let translation: CGPoint = recognizer.translation(in: self.view)
    var newY = view.center.y + translation.y
        startingPoint = recognizer.view!.center
        recognizer.view?.superview?.bringSubviewToFront(recognizer.view!)
        if newY > translation.y
        {
            recognizer.view?.center = CGPoint(x: recognizer.view!.center.x, y: recognizer.view!.center.y + translation.y)
            newY = view.center.y + translation.y
            recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
            //startingPoint = recognizer.view!.center
        }

它会上下移动,但我只希望它向上移动。

1 个答案:

答案 0 :(得分:0)

您正在比较错误的变量,并且Y值沿向下方向增加。您需要检查的是transition.y是否为负(即向上移动):

替换此:

if newY > translation.y

与此:

if transition.y < 0

实际上,根本不需要newY

@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.view)
    guard let view = recognizer.view else { return }

    view.superview?.bringSubviewToFront(view)

    // If the movement is upward (-Y direction):
    if translation.y < 0
    {
        view.center = CGPoint(x: view.center.x, y: view.center.y + translation.y)
        recognizer.setTranslation(.zero, in: self.view)
    }
}

注释:

其他更改:

  1. 使用guard安全地解包recognizer.view一次,而不是在整个代码中重复解包。
  2. CGPoint(x: 0, y: 0)替换为.zero,Swift认为CGPoint.zeroCGPoint