如何使用 Swipe 手势识别器进行长按?

How to use Swipe gesture recognizer for a long press up?

我正在使用滑动手势识别器通过向上滑动和向下滑动来增加和减少我的计数器。

我还在向上滑动时将标签偏移 +10,向下滑动时偏移 -10。

一切都很好,但是向上滑动后,我的标签偏移量又回到了 0。 我的目标是在向上滑动时将偏移量保持在 +10。 这是我的代码:

private func setupSwipeGestures() {
   var swipeUp = UISwipeGestureRecognizer(target: self, action:  Selector("handleSwipes:"))
   var swipeDown = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))

   swipeUp.direction = .Up
   swipeDown.direction = .Down

   view.addGestureRecognizer(swipeUp)
   view.addGestureRecognizer(swipeDown)
 }

func handleSwipes(sender:UISwipeGestureRecognizer) {
   let increment: Int
   let offset: CGFloat

   // up or down
    if sender.direction == .Up {
      increment = 1
      offset = 10
    } else {
      increment = -1
      offset = -10
   }

问题:

据我所知,你想在向上滑动时存储 +10 值,你可以通过购买将 incrementoffset 全局声明为 class 来实现如下所示:

class ViewController: UIViewController {

    //Declare it below your class declaration 
    var increment = 0
    var offset: CGFloat = 0

}

在你的代码中,你将这两个变量声明到你的 handleSwipes 函数中,这样当你调用这个函数时它将变为 0 并且你的偏移量将始终变为 +10 或 -10 但是一旦你全局声明它进入 class 后,它会保持它的值,如果你想在每次 handleSwipes 函数调用时增加它,那么你可以这样做:

offset +=  10
offset -= 10

您的 increment 变量也会发生同样的事情,您可以根据需要更改它,然后您可以通过这种方式将标签位置更改为您的 handleSwipes 函数:

yourLbl.center = CGPoint(x: yourLbl.center.x, y: yourLbl.center.y + offset)

您的 handleSwipes 函数将是:

func handleSwipes(sender:UISwipeGestureRecognizer) {


    // up or down
    if sender.direction == .Up {
        increment = 1
        offset +=  10
        println(offset)
        yourLbl.center = CGPoint(x: yourLbl.center.x, y: yourLbl.center.y + offset)
    } else {
        increment = -1
        offset -= 10
        println(offset)
        yourLbl.center = CGPoint(x: yourLbl.center.x, y: yourLbl.center.y + offset)
    }
}

希望这会有所帮助。