我正在尝试在 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)