Search code examples
swiftuigesturerecognizer

How to add a double tap Gesture Recognizer in Swift


I have already accomplished a single tap recognizer but can not figure out how to make that single tap recognizer a double tap instead. I could use some guidance.

Code:

import Foundation
import UIKit

class MainBoardController: UIViewController{

    let tap = UITapGestureRecognizer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "GotoProfile")
        swipe.direction = UISwipeGestureRecognizerDirection.Right
                    self.view.addGestureRecognizer(swipe)

        tap.addTarget(self, action: "GotoCamera")
        view.userInteractionEnabled = true
        view.addGestureRecognizer(tap)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func GotoProfile(){
        self.performSegueWithIdentifier("Profilesegue", sender: nil)
    }

    func GotoCamera(){
        self.performSegueWithIdentifier("Camerasegue", sender: nil)
    }
}

Solution

  • I solved this with an extension:

    override func viewDidLoad() {
        super.viewDidLoad()
                
        let tapGR = UITapGestureRecognizer(target: self, action: #selector(PostlistViewController.handleTap(_:)))
        tapGR.delegate = self
        tapGR.numberOfTapsRequired = 2
        view.addGestureRecognizer(tapGR)
    }
    

    extension MainBoardController: UIGestureRecognizerDelegate {
        func handleTap(_ gesture: UITapGestureRecognizer){
            print("doubletapped")
        }
    }