Search code examples
swiftuipangesturerecognizer

Swift: How do you get the velocity for each touches with UIPanGestureRecognizer?


I would like to get the velocity for each touches using UIPanGestureRecognizer like what you can do with the location of the touches using the method location(ofTouch: Int, in: UIView). However, when I use the method velocity(in: view), it only returns one of the velocities of the touches. I tried changing the maximumNumberOfTouches property but it didn't work.

Is there any way you can achieve this?


Solution

  • Ok, so I solved this by creating a 2d array of CGPoint called touchLocations and another array of CGPoint called touchVelocities. In a for loop looping through all the touches, I added

    if !touchLocations.indices.contains(touchNumber) {
        touchLocations.append([CGPoint]())
    }
    touchLocations[touchNumber].append(sender.location(ofTouch: touchNumber, in: view))
    

    to assign a new CGPoint for each touches (touchNumber is the index of the touch and sender is the gesture recognizer).

    Then I added

    touchLocations[touchNumber] = touchLocations[touchNumber].suffix(2)
    

    So that the array only contains the last 2 elements.

    To get the velocity, I simply did

    touchVelocities.insert(CGPoint(x: touchLocations[touchNumber].last!.x - touchLocations[touchNumber].first!.x, y: touchLocations[touchNumber].last!.y - touchLocations[touchNumber].first!.y), at: touchNumber)
    

    (Subtracted the first x value from the second x value for the x velocity, and did the same thing for the y velocity)

    I know this method is not very accurate, however it was good enough for my purposes.