简体   繁体   English

如何设置平移手势的 y 轴范围?

[英]How do I set limits in the y-axis for a Pan Gesture?

I want to limit my imageview to specific y-coordinates, but every-time I drag it over or below the 2-coordinates, the view gets stuck and doesn't move again.我想将我的 imageview 限制为特定的 y 坐标,但是每次我将它拖到 2 坐标上方或下方时,视图都会卡住并且不再移动。 Also, if I drag fast enough, the imageView goes above or below the coordinates that i limited it to.此外,如果我拖得足够快,imageView 会高于或低于我限制的坐标。

@IBAction func handlePan(_ gesture: UIPanGestureRecognizer) {
      // 1
      let translation = gesture.translation(in: view)

      // 2
      guard let gestureView = gesture.view else {
        return
      }
        
        if gestureView.center.y >= 161 && gestureView.center.y <= 561 {
            gestureView.center.y = gestureView.center.y + translation.y
            gesture.setTranslation(.zero, in: view)
        }
        
      // 3
      gesture.setTranslation(.zero, in: view)
    }

Instead of just not moving the image view at all when its y coordinate is outside of the specified range, you should still allow the image view to be moved downwards if it is too high, and upwards if it is too low.当图像视图的 y 坐标超出指定范围时,不要仅仅移动它,如果它太高,你仍然应该允许它向下移动,如果它太低,则向上移动。

It would be easier to specify in which situations you don't want the image view to be moved:指定在哪些情况下希望移动图像视图会更容易:

  • y < 161 and panning upwards y < 161 并向上平移
  • y > 561 and panning downwards y > 561 并向下平移

Also, the reason why you can move it out of the valid y range by dragging very fast is because you only check whether the image view's y coordinate is in the range before moving it, but not after.此外,您可以通过快速拖动将其移出有效 y 范围的原因是因为您只检查图像视图的 y 坐标是否在移动之前的范围内,而不是之后。 You should instead clamp the values when adding translation.y .您应该在添加translation.y钳制这些值。

@IBAction func handlePan(_ gesture: UIPanGestureRecognizer) {
    // 1
    let translation = gesture.translation(in: view)

    // 2
    guard let gestureView = gesture.view else {
        return
    }

    // in these two cases, don't translate the image view
    if (gestureView.center.y < 161 && translation.y < 0) ||
        (gestureView.center.y > 561 && translation.y > 0) {
        gesture.setTranslation(.zero, in: view)
        return
    }

    // clamping the translated y 
    gestureView.center.y = min(max(gestureView.center.y + translation.y, 161), 561)
    gesture.setTranslation(.zero, in: view)
}

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

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