首页 > 解决方案 > UISwipeGestureRecognizer 不适用于呈现的 VC 和视图

问题描述

层次结构:

初始化程序中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()可能会打乱手势操作的层次结构,但我不太确定。

标签: iosswiftselectoruiswipegesturerecognizerpresentviewcontroller

解决方案


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

下面的演示代码使用上面的工作。使用 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)
    }
}

推荐阅读