ios - UISwipeGestureRecognizer 不适用于呈现的 VC 和视图
问题描述
层次结构:
MainVC 调用
present(GameVC, animated: true, completion: nil)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "GameVC") as! GameVC self.present(vc, animated: true, completion: nil)
GameVC
hasGameView
(subclass ofUIView
) 涵盖了整个 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()
可能会打乱手势操作的层次结构,但我不太确定。
解决方案
您必须表明您的手势可以通过提供相应的委托方法来同时处理。
下面的演示代码使用上面的工作。使用 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)
}
}
推荐阅读
- entity-framework - 自动迁移不起作用 [EF Core]
- jquery - 使用 Webpack 4 时如何访问入口文件中的 jQuery 对象 ($)?
- scala - spark.streaming.backpressure.* 属性是否适用于 Spark 结构化流?
- python - 将值列表作为选项传递给 3 个下拉菜单
- laravel - Laravel - 我不明白为什么我的按钮没有打开多个折叠
- android - java.lang.String 类型的用户无法转换为 JSONObject json 响应 android
- php - mysqli num行的php问题不起作用
- tcp - Influxdb 不关闭 TCP 连接
- javascript - 是否可以使用 JS 正则表达式向 html 添加格式
- c# - 反序列化 JSON 错误将值转换为特定类型