什么代码可用于检测用户何时与应用交互以及何时不与应用交互?
目前我有一个 ViewController
和一个 UIView
,它通过覆盖触摸接收触摸,也通过接收平移手势和点击手势。这个问题的解决方案需要与当前的手势分开或置于这些手势之上。
是否有一个高于一切的手势识别器可以告诉我的应用何时收到手势以及何时没有收到手势?
当应用程序处于事件状态时,是否有一种方法可以监控应用程序是否正在接收触摸以及何时未接收触摸并根据需要调用函数,例如:
func appActive(){
print("App received input from a touch, tap, swipe, long press etc.")
}
func appInactive(){
print("App stopped receiving any input.")
}
谢谢。
Swift 2. Xcode 7.2. Tested on iOS 7 - 9.
Adapted from:
How to detect all touches in Swift 2
and
Subclass UIApplication with Swift
1 - 找到项目的 Swift 文件 AppDelegate.swift
,然后注释掉 @UIApplicationMain
:
//@UIApplicationMain
2 - 将一个新的 Swift 文件添加到您的项目中,完全命名为 main.swift
,并添加代码:
import UIKit
UIApplicationMain(
CommandLine.argc, UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory( to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)), nil, NSStringFromClass(AppDelegate.self))
3 - 将新的 Swift 文件添加到您的项目中,完全命名为 UIApplication.swift
,并添加代码:
import UIKit
@objc(MyApplication)
class MyApplication: UIApplication {
override func sendEvent(event: UIEvent) {
// Ignore .Motion and .RemoteControl event simply everything else then .Touches
if event.type != .Touches {
super.sendEvent(event)
return
}
// .Touches only
var restartTimer = true
if let touches = event.allTouches() {
// At least one touch in progress? Do not restart timer, just invalidate it
for touch in touches.enumerate() {
if touch.element.phase != .Cancelled && touch.element.phase != .Ended {
restartTimer = false
break
}
}
}
if restartTimer {
// Touches ended || cancelled, restart timer
print("Touches ended. Restart timer")
} else {
// Touches in progress - !ended, !cancelled, just invalidate it
print("Touches in progress. Invalidate timer")
}
super.sendEvent(event)
}
}
4 - 找到您项目的 Info.plist
文件,并添加一个新键(Xcode 菜单:Editor > Add Item
),选择或键入键 Principal class
,字符串值为 MyApplication
。
5 - 运行你的项目!