层次结构:
present(GameVC, animated: true, completion: nil)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "GameVC") as! GameVC
self.present(vc, animated: true, completion: nil)
GameVC
有 GameView
(UIView
的子类),涵盖整个 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(通过将 Storyboard 箭头拖到 GameVC
上),手势按预期工作。 这让我觉得调用 present()
可能弄乱了手势操作的层次结构,但我不太确定。
最佳答案
您必须表明您的手势可以通过提供相应的委托(delegate)方法来同时处理。
下面的演示代码使用上面的工作。使用 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)
}
}
关于ios - UISwipeGestureRecognizer 不适用于呈现的 VC 和 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61175403/