Search code examples
iosswiftuigesturerecognizergesturetarget

How to pass multiple parameters in UILongPressGestureRecognizer iOS Swift 4?


I want to pass some parameters with UILongPressGestureRecognizer method in iOS Swift 4.* .

let buttonLongGesture = UILongPressGestureRecognizer(target: self, action: #selector(buttonPressedLong(_:)))
button.addGestureRecognizer(buttonLongGesture)

@objc func buttonPressedLong(_ sender:UIGestureRecognizer) {

}

Solution

  • I would suggest you make a custom class inherit UI LongPressGestureRecognizer then you can add any parameters as variables there. Finally you can use it to send parameters when the gesture happens. Here's an example.

    class CustomLongPressGesture: UILongPressGestureRecognizer {
        var firstParam: String!
        var secondParam: String!
    }
    

    Then you can implement it like this:

    func setUp() {
        let buttonLongGesture = CustomLongPressGesture(target: self, action: #selector(buttonPressedLong(_:)))
        buttonLongGesture.firstParam = "Test"
        buttonLongGesture.secondParam = "Second Test"
        button.addGestureRecognizer(buttonLongGesture)
    }
    
     @objc func buttonPressedLong(_ sender: CustomLongPressGesture) {
        print(sender.firstParam, sender.secondParam) // Access it here
     }