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

How to track all touches across SwiftUI app

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

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

在 UIKit 应用程序中,我使用了这种方法 - 覆盖 UIApplication,它允许了解应用程序中的任何事件:

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
    }
}

基于 ,我添加了 UIPanGestureRecognizer 以便在滚动或滑动应用时也能够识别。还添加了一个通知观察器以识别何时从键盘输入文本。解决方案如下所示:

@main
struct YourApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {
                    // Interaction recognizer implementation
                    UIApplication.shared.addInteractionRecognizer()
                }
        }
    }
}

extension UIApplication {
    func addInteractionRecognizer() {
        // Notification observer to track text changes from keyboard
        NotificationCenter.default.addObserver(self, selector: #selector(didInteractWithApp), name: UITextField.textDidChangeNotification, object: nil)
        
        guard let window = windows.first else { return }
        
        // Gestures recognizers to track
        let gestureRecognizers = [
            UITapGestureRecognizer(target: self, action: #selector(didInteractWithApp)),
            UIPanGestureRecognizer(target: self, action: #selector(didInteractWithApp))
        ]
        
        gestureRecognizers.forEach {
            [=10=].requiresExclusiveTouchType = false
            [=10=].cancelsTouchesInView = false
            [=10=].delegate = self
            window.addGestureRecognizer([=10=])
        }
    }
    
    @objc func didInteractWithKeyboard() {
        // Restart the lock timer
    }
    
    @objc func didInteractWithApp(_ sender: UIGestureRecognizer) {
        // Optional: Validate UIPanGestureRecognizer has ended, cancelled or failed, to prevent overloading for restarting timer. Remove if not needed
        let allowedStates: [UIGestureRecognizer.State] = [.ended, .cancelled, .failed]
        if sender as? UIPanGestureRecognizer != nil, !allowedStates.contains(sender.state) {
            return
        }
        
        // Restart the lock timer
    }
}

extension UIApplication: UIGestureRecognizerDelegate {
    public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // Set to true to recognize gestures specified above while allowing user interact with other gestures in the app and not to block them with them
        return true
    }
}