我设置了以下 Swift 2 代码,可以捕获整个应用程序中的所有触摸。它会在触摸发生和触摸停止时发出警报。
我想访问另一个视图控制器中的两个函数,命名myVC
为何时发生触摸以及何时停止,调用函数一funcOne()
和函数二funcTwo()
。但是我不断收到错误fatal error: unexpectedly found nil while unwrapping an Optional value
。似乎无论何时myVC
调用,它都会导致错误。
如何在没有错误的情况下在 ViewController 上调用函数,请取决于应用程序何时接收或不接收 Swift 2 中的任何触摸事件?
main.swift
文件:
import UIKit
UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))
UIApplication.swift
文件:
import UIKit
@objc(MyApplication)
class MyApplication: UIApplication {
var myVC: ViewController!
override func sendEvent(event: UIEvent) {
if event.type != .Touches {
super.sendEvent(event)
return
}
var touchesStarted = false
if let touches = event.allTouches() {
for touch in touches.enumerate() {
if touch.element.phase != .Cancelled && touch.element.phase != .Ended {
touchesStarted = true
break
}
}
}
if touchesStarted {
myVC.funcOne() // Call function one on ViewController
} else {
myVC.funcTwo() // Call function two on ViewController
}
super.sendEvent(event)
}
}