UISwipeGestureRecognizer 不适用于呈现的 VC 和视图

UISwipeGestureRecognizer doesn't work on presented VC and view

层次结构:

GameView 初始化器中,我有这段代码来配置滑动手势:

let leftGesture = UISwipeGestureRecognizer(target: self, action: #selector(leftSwipe))
leftGesture.direction = .left
self.addGestureRecognizer(leftGesture)

let rightGesture = UISwipeGestureRecognizer(target: self, action: #selector(rightSwipe))
rightGesture.direction = .right
self.addGestureRecognizer(rightGesture)

let downGesture = UISwipeGestureRecognizer(target: self, action: #selector(downSwipe))
downGesture.direction = .down
self.addGestureRecognizer(downGesture)

对应的选择器:

@objc func downSwipe() {
    //code
}

@objc func leftSwipe() {
    //code
}

@objc func rightSwipe() {
    //code
}

没有调用选择器。但是,当我将 GameVC 设置为正在显示的初始 VC 时(通过将故事板箭头拖到 GameVC 上), 手势按预期工作。 这让我觉得调用 present() 可能会弄乱手势操作的层次结构,但我不太确定。

你必须说明你的手势可以通过提供相应的委托方法来同时处理。

下面的演示代码可以使用上面的代码。使用 Xcode 11.4 / iOS 13.4

测试
class GameView: UIView {
}

// in Storyboard just empty view of above custom GameView
class GameVC: UIViewController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftGesture = UISwipeGestureRecognizer(target: self, action: #selector(leftSwipe))
        leftGesture.direction = .left
        leftGesture.delegate = self
        self.view.addGestureRecognizer(leftGesture)

        let rightGesture = UISwipeGestureRecognizer(target: self, action: #selector(rightSwipe))
        rightGesture.direction = .right
        rightGesture.delegate = self
        self.view.addGestureRecognizer(rightGesture)

        let downGesture = UISwipeGestureRecognizer(target: self, action: #selector(downSwipe))
        downGesture.direction = .down
        downGesture.delegate = self
        self.view.addGestureRecognizer(downGesture)

    }

    // allows own view gestures to run with system originated simultaneously
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        true
    }

    @objc func downSwipe() {
        print(">> down swipe")
    }

    @objc func leftSwipe() {
        print(">> left swipe")
    }

    @objc func rightSwipe() {
        print(">> right swipe")
    }
}

// Initial VC, in storyboard contains only button linked to below showGame action
class ViewController: UIViewController {

    @IBAction func showGame(_ sender: Any) {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "GameVC") as! GameVC
        self.present(vc, animated: true, completion: nil)
    }
}