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

763 views Asked by At

I'm using a swipe gesture recognizer to increase and decrease my counter with a swipe up and a swipe down.

I'm also offsetting my label by +10 when I swipe up and -10 when I swipe down.

everything is fine but once I swipe up, my label offset comes back to 0. My goal is to leave the offset at +10 as long as I'm swiping up. Here is my code:

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
   }

Question:

  • Is there a solution to keep the label at an offset of +10 as long as I'm swiping up, and at an offset of -10 as long as I'm swiping down?
1

There are 1 answers

0
Dharmesh Kheni On BEST ANSWER

As I understand from your question you want to store that +10 value when you swipe up and you can do it buy declaring your increment and offset globally into class like shown below:

class ViewController: UIViewController {

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

}

In your code you are declaring this two variables into your handleSwipes function so that when you call this function it will become 0 and your offset will always become +10 or -10 but once you declare it globally into class it will hold its value once it gets and If you want to increment it every time when handleSwipes function call then you can do it this way:

offset +=  10
offset -= 10

Same thing will happend to your increment variable you can change it as per your need and after that you can change label position this way into your handleSwipes function :

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

And your handleSwipes function will be:

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)
    }
}

Hope this will help.