在 UIApplication 中捕获触摸并在 ViewController 中调用函数导致错误

Capturing touches in UIApplication and calling a function in ViewController causing error

我设置了以下 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)
    }
}

问题是你说的

 var myVC: ViewController!

但您永远不会将变量myVC设置为任何值(即现有的ViewController实例)。因此它始终是 nil,因此当您在代码中引用它时,您会崩溃。

我的建议是这个视图控制器,在它自己的 viewDidLoad 中应该说

(UIApplication.sharedApplication() as MyApplication).myVC = self