Search code examples
iosswiftipados

Using numberOfTouchesRequired to implement secondary click with TrackPad


I want to implement the secondary click on iPad to show options.

let tapTwoRecog = UITapGestureRecognizer(target: self, action: #selector(tapTwoAsLongPress(gesture:)))
        tapTwoRecog.numberOfTouchesRequired = 2
        tapTwoRecog.numberOfTapsRequired = 1
        tapTwoRecog.allowedTouchTypes = [NSNumber(value: UITouch.TouchType.direct.rawValue), NSNumber(value: UITouch.TouchType.indirect.rawValue)]
        tableView.addGestureRecognizer(tapTwoRecog)
        tableView.isMultipleTouchEnabled = true

But it only be triggered by the touches on the screen. Using trackpad doesn't trigger anything. I've already set the UIApplicationSupportsIndirectInputEvents to YES/NO.


Solution

  • I just found an answer from this site: https://pspdfkit.com/blog/2020/level-up-your-trackpad-support-using-uiinteraction/

    if #available(iOS 13.4, *) {
        let tapTwoRecog = UITapGestureRecognizer(target: self, action: #selector(tapTwoAsLongPress(gesture:)))
        tapTwoRecog.allowedTouchTypes = [NSNumber(value: UITouch.TouchType.indirectPointer.rawValue)]
        tapTwoRecog.buttonMaskRequired = .secondary
        tableView.addGestureRecognizer(tapTwoRecog)
    }
    

    The UIApplicationSupportsIndirectInputEvents must be YES.