简体   繁体   English

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

[英]Limiting pan gesture to one direction

Would like to have the image only pan upwards. 希望图像仅向上平移。

I have tried to edit the x and y coordinates. 我试图编辑x和y坐标。 Tried to to make a new y variable based on the translation but does not change. 尝试根据转换生成新的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
        }

It will pan up and down but I only want it to go up. 它会上下移动,但我只希望它向上移动。

You are comparing the wrong variables, and Y values increase in the downward direction. 您正在比较错误的变量,并且Y值沿向下方向增加。 All you need to check is that transition.y is negative (ie. moving upward): 您需要检查的是transition.y为负(即向上移动):

Replace this: 替换为:

if newY > translation.y

with this: 有了这个:

if transition.y < 0

In fact, newY isn't really needed at all: 实际上, newY不需要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)
    }
}

Notes: 笔记:

Other changes made: 进行的其他更改:

  1. Used guard to safely unwrap recognizer.view once instead of repeatedly unwrapping it throughout the code. 使用过guard可以安全地一次解开recognizer.view .view,而不是在整个代码中反复解开它。
  2. Replaced CGPoint(x: 0, y: 0) with .zero which Swift infers to be CGPoint.zero since it is expecting a CGPoint . .zero替换了CGPoint(x: 0, y: 0) ,Swift推断它为CGPoint.zero因为它期望一个CGPoint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM