Swift: Getting target of UIPanGestureRecognizer

3k views Asked by At

In my ViewController.swift, I have an array that contains custom UIViews. Every time one is created, I add a UIPanGestureRecognizer to it like this:

var panRecognizer = UIPanGestureRecognizer(target: self, action: "detectPan:")
newCard.gestureRecognizers = [panRecognizer]

This links to my detectPan(recognizer: UIPanGestureRecognizer) function, which handles movement. However, since I have multiple objects linked to the function, I'm not sure how I determine from which one the input is coming.

Is there anything like (the nonexistent) recognizer.target that I could use? Should I just handle the panning from within each of the custom UIViews instead?

Any help would be appreciated!

1

There are 1 answers

1
ndmeiri On BEST ANSWER

First of all, you should declare your panRecognizer with let.

let panRecognizer = UIPanGestureRecognizer(target: self, action: "detectPan:")

Second of all, you should not set the gestureRecognizers property of any UIView. This is bad practice because UIKit may have already added its own gesture recognizers to that view behind the scenes. If you subsequently remove those recognizers by assigning [panRecognizer] to that property, you may get unexpected behavior. To add your pan gesture recognizer, do this:

newCard.addGestureRecognizer(panRecognizer)

Then, in your detectPan(recognizer: UIPanGestureRecognizer) method you can detect which UIView was panned with the following code:

func detectPan(recognizer: UIPanGestureRecognizer) {
    switch recognizer.view {
    case self.customViewArray[0]:
        // do something
    case self.customViewArray[1]:
        // do something else
    case ... :
    // ...
}