AliDeV
AliDeV

Reputation: 213

How to implement double tap for further action like for more information?

I have implemented a switch statement. Now I am struggling to add a double tap gesture to dispaly a more information depnding on the case chosen from the switch.


override func viewDidLoad() {

    let tap = UITapGestureRecognizer(target: self, action: #selector(moreInfo))
    tap.numberOfTapsRequired = 2
    view.addGestureRecognizer(tap)
}

// the main switch case
switch choice {
case 1:
    print("1 is chosen")
    moreInfo(option:1)
case 2:
    print("2 is chosen")
    moreInfo(option:2)

}


//to be activated when double tap 
@objc func moreInfo(option: Int) {
    switch choice {
    case 1:
        print("more information for 1")

    case 2:
        print("more information for 2")
    }
}

Upvotes: 0

Views: 43

Answers (1)

Won
Won

Reputation: 1226

I just write some example code. Hope it help.

Like below code, you can use double and single tap actions.

class ViewController: UIViewController {

    var singleTap: UITapGestureRecognizer!
    var doubleTap: UITapGestureRecognizer!

    override func viewDidLoad() {
        super.viewDidLoad()

        doubleTap = UITapGestureRecognizer(target: self, action: #selector(tap(gesture:)))
        view.addGestureRecognizer(doubleTap)
        doubleTap.numberOfTapsRequired = 2
        doubleTap.delaysTouchesBegan = true

        singleTap = UITapGestureRecognizer(target: self, action: #selector(tap(gesture:)))
        singleTap.delaysTouchesBegan = true
        singleTap.require(toFail: doubleTap)
        view.addGestureRecognizer(singleTap)
    }

    @objc
    func tap(gesture: UITapGestureRecognizer) {
        switch gesture {
        case singleTap:
            moreInfo(option: 1)
        case doubleTap:
            moreInfo(option: 2)
        default:
            print("---")
        }
    }

    func moreInfo(option: Int) {
        switch option {
        case 1:
            print("more information for 1")

        case 2:
            print("more information for 2")
        default:
            print("---")
        }
    }
}

Upvotes: 1

Related Questions