斯威夫特 2.Xcode 7.2。在 iOS 7 - 9 上测试。
改编自:
如何在 Swift 2 中检测所有触摸 https://stackoverflow.com/questions/31642956/how-to-detect-all-touches-in-swift-2
and
使用 Swift 子类化 UIApplication https://stackoverflow.com/questions/24020000/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 - 运行您的项目!