【发布时间】:2021-07-30 10:20:16
【问题描述】:
我想要
- 检测屏幕任意位置的全局修饰事件
- 不会影响按钮、自定义视图等组件。下面的按钮,自定义视图仍然能够接收点击事件。
我做的是
- 在
UIApplication.shared.keyWindow中安装UITapGestureRecognizer - 在
UIGestureRecognizerDelegate中,为shouldRecognizeSimultaneouslyWith返回true,这样顶级keyWindow 就不会阻止按钮、自定义视图接收点击事件。
这是我的代码
import UIKit
extension UIWindow {
static var key: UIWindow! {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer)
-> Bool {
print(">>> shouldRecognizeSimultaneouslyWith returns true")
return true
}
}
class ViewController: UIViewController {
// Lazy is required as self is not ready yet without lazy.
private lazy var globalGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(globalTapped))
private func installGlobalGestureRecognizer() {
UIWindow.key.removeGestureRecognizer(globalGestureRecognizer)
UIWindow.key.addGestureRecognizer(globalGestureRecognizer)
globalGestureRecognizer.delegate = self
}
@objc func globalTapped() {
print(">>> global tapped")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonClicked(_ sender: Any) {
print("yellow button tap\n")
}
@IBAction func handleTap(_ gesture: UITapGestureRecognizer) {
print("red view tap\n")
}
@IBAction func installButtonClicked(_ sender: Any) {
print("install global gesture")
installGlobalGestureRecognizer()
}
}
这是点击红色自定义视图时发生的情况
点击红色自定义视图时(按预期工作)
install global gesture
>>> shouldRecognizeSimultaneouslyWith returns true
>>> shouldRecognizeSimultaneouslyWith returns true
>>> global tapped
red view tap
点击黄色按钮时(全局手势不起作用)
install global gesture
yellow button tap
这就是我为自定义红色视图和黄色按钮安装点击事件处理程序的方式。
有谁知道,为什么在点击按钮时不调用shouldRecognizeSimultaneouslyWith?我希望在点击黄色按钮时
-
shouldRecognizeSimultaneouslyWith执行并返回 true - 黄色按钮点击事件处理程序已执行
- 已执行全局手势点击事件处理程序
谢谢。
【问题讨论】:
-
部分问题是
UIControl上的.touchUpInside不是Tap 手势。您可能需要另一种方法。这是一篇可能值得一读的(较旧的)文章:dzone.com/articles/… ...您可能想通过Combine查看接收和处理事件 -
我在your previous question 中发布了一个适用于所有情况的全局修饰的简单解决方案。它不符合您的要求吗?还是你没看到