如何访问 UIApplication 子类函数

How to access UIApplication subclass functions

我有 VC1,它是 UIApplication 的子类

VC1

   class CustomUIApplication: UIApplication {
       override func sendEvent(_ event: UIEvent) {
            super.sendEvent(event)
       }
            
       func stopTimer() {
                   
       }
            
       func startTimer() {
                    
       }
   }

VC2

class MyVC: ViewController {
   // want to access start timer func here
}

CustomUIApplication 的实例将在 main.swift

UIApplicationMain(
    CommandLine.argc,
    CommandLine.unsafeArgv,
    NSStringFromClass(CustomUIApplication.self),
    NSStringFromClass(AppDelegate.self)
)

如有任何帮助,我们将不胜感激并提前致谢。

根据文档:

Every iOS app has exactly one instance of UIApplication (or, very rarely, a subclass of UIApplication). When an app is launched, the system calls the UIApplicationMain(::::) function; among its other tasks, this function creates a Singleton UIApplication object. Thereafter you access the object by calling the shared class method.

所以在 MyVC 中你应该可以做到 CustomUIApplication.shared.startTimer().

也就是说,我可以建议您考虑使用单独的 class 来处理 start/stop 时间功能,而不是使用 UIApplication 的子 class 吗?您可以为此创建自己的单例,并以类似的方式从您需要的任何地方访问它。

编辑:当然,你得先定义static var shared: Self { UIApplication.shared as! Self }。 (根据 @Sulthan 的评论)