2

I have managed to get x and y start coordinates during a swipe:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let position :CGPoint = touch.locationInView(view)
        startX = Int(position.x)
        startY = Int(position.y)        
    }
}

I need the y coordinates during the swipe as well. I have managed to do this in a very roundabout kind of way with the UIPanGestureRecognizer.

There must be some way to make it in as few lines as getting the starting coordinates.

Can anyone help point me in the right direction?

Best regards, Niklas

danywarner
  • 928
  • 2
  • 15
  • 28
Niklas
  • 75
  • 2
  • 9
  • Do you want to use `UIPanGestureRecognizer` or are you trying to implement this yourself with the `touchesBegan`, `touchesMoved`, etc methods? – Carter Jul 29 '16 at 20:13
  • This might help http://stackoverflow.com/a/34756033/2303865 – Leo Dabus Jul 29 '16 at 20:48
  • @Carter, I think that `UIPanGestureRecognizer` or `touchesMoved` doesn't really matter as long as I can get the Y coordinates during the swipe. @LeoDabus, I read through the page you linked but didn't find out how to get the Y coordinates. I'm pretty new to this so it might be there even though i don't see it. – Niklas Jul 30 '16 at 09:28

2 Answers2

4

You can use UIPanGestureRecognizer for this. It will give you both the x and y coordinates of the swipe. Apple created this specifically for this scenario- it is easier to implement than touchesMoved and tracking everything yourself.

To set up your gesture recognizer:

let gestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.someDraggableView.addGestureRecognizer(gestureRecognizer)

To get the translation (in the callback you set up above):

func handlePan(gestureRecognizer: UIPanGestureRecognizer) {
    if gestureRecognizer.state == .Began {
        // When the drag is first recognized, you can get the starting coordinates here
    }

    if gestureRecognizer.state == .Changed {
        let translation = gestureRecognizer.translationInView(self.view)  
        // Translation has both .x and .y values
    }
}

In the .Changed part of the callback, your code will be called each time the user moves their finger in the given view. You can get the y coordinate from translation.y

You can see more examples here.

Community
  • 1
  • 1
Carter
  • 3,053
  • 1
  • 17
  • 22
  • **`thankYou!`** That's exactly what I was after. It saved me an embarrassing lot of code lines. :-) – Niklas Jul 30 '16 at 18:24
0

Looks like you looking for the method 'touchesMoved'. I am doing this answer on a phone so can't get the format correct

impression7vx
  • 1,728
  • 1
  • 20
  • 50