UISwipeGestureRecognizer在显示的VC和视图上不起作用

问题描述 投票:0回答:1

层次结构:

  • MainVC调用present(GameVC, animated: true, completion: nil)

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "GameVC") as! GameVC self.present(vc, animated: true, completion: nil)

  • [GameVC具有GameViewUIView的子类),它覆盖了整个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
}

选择器没有被调用。但是,当我将要显示的初始VC设为GameVC时(通过将情节提要板箭头拖到GameVC上),手势可以按预期的方式工作。这使我认为调用present()可能会混乱手势操作的层次结构,但我不太确定。

ios swift selector uiswipegesturerecognizer presentviewcontroller
1个回答
0
投票

您必须指出,通过提供相应的委托方法可以同时处理您的手势。

下面的演示代码可以在上面使用。使用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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.