从 AppDelegate 检测 UIViewController 变化

Detect UIViewController change from AppDelegate

每次应用程序加载新的 ViewController(转换到不同的视图)时,我都会尝试执行一个函数。为了避免在每个 ViewController 中调用此函数(大约有 10 个,还有更多要添加),我希望通过添加某种观察者在 AppDelegate 中执行此操作。这可能吗?还是可以借助 UIViewController 扩展以某种方式完成?

忘记 AppDelegate、观察者或扩展,使用 Inheritance

您所有的 UIViewController 都应该扩展 MainViewController 基础 class,您可以将您的逻辑放在基础 class.

的 viewDidLoad 方法(或 viewDidAppear)中

记得在覆盖时调用超级class方法。

或者,您可以子类化 UINavigationController 和 post 您感兴趣的事件通知:

class NotificationNavigationController: UINavigationController {
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "NavigationControllerWillPush"), object: nil)
        super.pushViewController(viewController, animated: animated)
    }

    override func popViewController(animated: Bool) -> UIViewController? {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "NavigationControllerWillPop"), object: nil)
        return super.popViewController(animated: animated)
    }
}

然后在您的 Application Delegate 中您可以观察到这些通知:

NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "NavigationControllerWillPush"), object: nil, queue: OperationQueue.main) {
            notification in
            // handle push
        }
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "NavigationControllerWillPop"), object: nil, queue: OperationQueue.main) {
            notification in
            // handle pop
        }