【问题标题】:How to use Swipe gesture recognizer for a long press up?如何使用滑动手势识别器进行长按?
【发布时间】:2015-06-11 03:48:32
【问题描述】:

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

当我向上滑动时,我的标签也会偏移 +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 的偏移量?

【问题讨论】:

    标签: ios swift uigesturerecognizer


    【解决方案1】:

    从您的问题中了解到,您希望在向上滑动时存储 +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)
        }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多