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

标签 ios swift uigesturerecognizer

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

当我向上滑动时,我也会将我的标签偏移 +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 的偏移量,而在向下滑动时保持 -10 的偏移量?

最佳答案

我从你的问题中了解到,你想在向上滑动时存储 +10 值,你可以通过购买声明你的 incrementoffset 全局到类中来做到这一点如下所示:

class ViewController: UIViewController {

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

}

在您的代码中,您将这两个变量声明到您的 handleSwipes 函数中,这样当您调用此函数时,它将变为 0,并且您的偏移量将始终变为 +10 或 -10,但是一旦您声明它全局进入类,一旦获得它就会保留它的值,如果你想在每次 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)
    }
}

希望这会有所帮助。

关于ios - 如何使用 Swipe 手势识别器进行长按?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771217/

相关文章:

swift - 在 collectionview 单元格中添加到 uiview 时点击手势无法按预期工作

ios - 如何在 iOS9 中禁用 interactivePopGestureRecognizer

ios - 使用 swift 和 flutter 集成 Stripe SDK

ios - 使用 Swift 返回的 block 调用 Objective-C 方法会导致 EXC_BAD_ACCESS

swift - 在 Swift 中获取带有前提条件的子序列的有效方法

objective-c - 在 Swift 中获取 Objective-C 接口(interface)?

ios - 如何在滑动时向下移动 ImageView ?

ios - 使用 Swift 在 iOS 中做出决定的最佳方式是什么

iphone - iOS - 允许用户从文档目录下载文件,但不允许使用 iTunes 上传文件

swift - 在 Swift 中使用 Timer() 的命令行工具