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

问题描述:

我设置了下面的Swift 2代码,捕获整个应用程序中的所有触摸。它在触摸发生和触摸停止时发出警报。在UIApplication中捕获触及并在ViewController中调用导致错误的函数

我想访问一个名为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 
+0

顺便问一下,你在做什么是一个非常糟糕的主意,这是完全没有必要的。通过继承UIWindow而不是UIApplication,您可以更安全地介入触摸处理,甚至更好地通过在所有内容之前的不可见视图在视图控制器级别进行干预。 – matt

+0

谢谢,@Matt。我如何设置myVC的变量为一个值? – user4806509

+0

我试过'UIWindow',但它不适用于所有手势和触摸组合。 'UIApplication'可以使用'print'来测试它。不过,我需要设置一个函数进入ViewController。 – user4806509