Search code examples
iosswiftuibuttonuigesturerecognizersender

Get Sender info from GestureRecognizer tied to multi UIButtons


So I have a UILongPressGestureRecognizer connected to

@IBAction func PresentPlayerInfo(sender: UIGestureRecognizer){
    if let button = sender.view as? UIButton {
        buttonSourceFrame = button.frame.origin}
    performSegueWithIdentifier("PVC", sender: self)
}

buttonSourceFrame is then passed to next ViewController in prepareForSegue

I want to connect this 1 UILongPressGestureRecognizer to multiple UIButtons so that I don't have to create a UILongPressGestureRecognizer for each UIButton.

But when I connect more than one UIButton to a single gestureRecognizer...No matter which button I press, the segue occurs fine but the CGPoint that's passed is always that of which ever UIButton is at the top of the list (here it's 3), instead of the CGPoint of the exact UIButton pressed.

enter image description here

Is it possible to connect a GestureRecognizer to many UIButtons and still get sender info...or do I HAVE to create a GestureRecognizer each UIButton?


Solution

  • Connect the gesture recognizer to the main view of your viewController. Then, in your @IBAction you have to determine the view which was tapped:

    @IBAction func PresentPlayerInfo(sender: UIGestureRecognizer){
        var tappedView: UIView?
        var loc = sender.locationInView(self.view)  // self.view is the parent view of the buttons
    
        if (CGRectContainsPoint(self.button1.frame, loc)) {
            tappedView = self.button1
        }
        else if (CGRectContainsPoint(self.button2.frame, loc)) {
            tappedView = self.button2
        }
    
    
        performSegueWithIdentifier("PVC", sender: tappedView)
    }