在 AppDelegate 中检测抖动
Detecting shake in AppDelegate
如何在 Swift 的 AppDelegate 中(跨整个应用程序)检测设备抖动?
我找到了描述如何在视图控制器中执行此操作的答案,但希望在我的应用程序中执行此操作。
在您的 AppDelegate
中添加以下代码段:
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
print("Device shaken")
}
}
Swift 3.0版本:
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken")
}
}
至于以后的版本,这似乎不再起作用了。您需要在视图控制器中添加以上代码
如果要全局检测抖动,UIWindow 实现了可以接收抖动事件的UIResponder。您可以将以下代码片段添加到 AppDelegate
extension UIWindow {
open override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken")
}
}
}
从 Swift 4 或 5 开始,它是 UIEvent.EventSubtype
,而不是 UIEventSubtype
。
另外不要忘记添加对 super.motionEnded(motion, with: event)
的调用。这会在您的视图控制器上保留任何 motionEnded 自定义设置。
extension UIWindow {
open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
super.motionEnded(motion, with: event)
if motion == .motionShake {
print("Device shaken")
}
}
}
如何在 Swift 的 AppDelegate 中(跨整个应用程序)检测设备抖动?
我找到了描述如何在视图控制器中执行此操作的答案,但希望在我的应用程序中执行此操作。
在您的 AppDelegate
中添加以下代码段:
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
print("Device shaken")
}
}
Swift 3.0版本:
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken")
}
}
至于以后的版本,这似乎不再起作用了。您需要在视图控制器中添加以上代码
如果要全局检测抖动,UIWindow 实现了可以接收抖动事件的UIResponder。您可以将以下代码片段添加到 AppDelegate
extension UIWindow {
open override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Device shaken")
}
}
}
从 Swift 4 或 5 开始,它是 UIEvent.EventSubtype
,而不是 UIEventSubtype
。
另外不要忘记添加对 super.motionEnded(motion, with: event)
的调用。这会在您的视图控制器上保留任何 motionEnded 自定义设置。
extension UIWindow {
open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
super.motionEnded(motion, with: event)
if motion == .motionShake {
print("Device shaken")
}
}
}