Ios 如何在SwiftUI应用程序中跟踪所有触摸

Ios 如何在SwiftUI应用程序中跟踪所有触摸,ios,swift,swiftui,ios14,Ios,Swift,Swiftui,Ios14,我正在尝试在SwiftUI应用程序中实现锁定屏幕 我需要跟踪每个事件以重新启动锁定计时器 在UIKit应用程序中,我使用了这种方法-覆盖UIKit应用程序,它允许在整个应用程序中感知任何事件: override func sendEvent(_ event: UIEvent) { super.sendEvent(event) switch event.type { case .touches: // Post Notification or Delegate here

我正在尝试在SwiftUI应用程序中实现锁定屏幕

我需要跟踪每个事件以重新启动锁定计时器

在UIKit应用程序中,我使用了这种方法-覆盖UIKit应用程序,它允许在整个应用程序中感知任何事件:

override func sendEvent(_ event: UIEvent) {
  super.sendEvent(event)

  switch event.type {
  case .touches:
    // Post Notification or Delegate here
  default:
    break
  }
}
但在SwiftUI中,它不再受支持。 我试图补充

.onTapGesture {}
到根ContentView,但它没有按预期工作

有没有办法避免添加

.onTapGesture {}

对于应用程序中的每个视图?

这里有一个可能的解决方案:

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear(perform: UIApplication.shared.addTapGestureRecognizer)
        }
    }
}

extension UIApplication {
    func addTapGestureRecognizer() {
        guard let window = windows.first else { return }
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        tapGesture.requiresExclusiveTouchType = false
        tapGesture.cancelsTouchesInView = false
        tapGesture.delegate = self
        window.addGestureRecognizer(tapGesture)
    }

    @objc func tapAction(_ sender: UITapGestureRecognizer) {
        print("tapped")
    }
}

extension UIApplication: UIGestureRecognizerDelegate {
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true // set to `false` if you don't want to detect tap during other gestures
    }
}

您可以看到以下答案:-您可以调用自定义函数,而不必重新编辑。是的,这是一个很好的答案,但是没有Scenedelegate和window的iOS 14存在一些问题。使用此代码时出现此错误
“windows”在iOS 15.0中被弃用:在相关的窗口场景中改用UIWindowScene.windows