Swift: Long Press Gesture Recognizer – Detect taps and Long Press

Define two IBActions and set one Gesture Recognizer to each of them. This way you can perform two different actions for each gesture.

You can set each Gesture Recognizer to different IBActions in the interface builder.

@IBAction func tapped(sender: UITapGestureRecognizer)
{
    println("tapped")
    //Your animation code.
}

@IBAction func longPressed(sender: UILongPressGestureRecognizer)
{
    println("longpressed")
    //Different code
}

Through code without interface builder

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
    self.view.addGestureRecognizer(tapGestureRecognizer)
    
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
    self.view.addGestureRecognizer(longPressRecognizer)

func tapped(sender: UITapGestureRecognizer)
{
    println("tapped")
}

func longPressed(sender: UILongPressGestureRecognizer)
{
    println("longpressed")
}

Swift 5

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
self.view.addGestureRecognizer(tapGestureRecognizer)
    
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
self.view.addGestureRecognizer(longPressRecognizer)
    
@objc func tapped(sender: UITapGestureRecognizer){
    print("tapped")
}

@objc func longPressed(sender: UILongPressGestureRecognizer) {
    print("longpressed")
}

Leave a Comment