从AppDelegate检测UIViewController更改

时间:2016-11-03 11:22:16

标签: ios swift uiviewcontroller appdelegate

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

2 个答案:

答案 0 :(得分:1)

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

所有的UIViewControllers都应该扩展一个MainViewController基类,你可以将你的逻辑放在基类的viewDidLoad方法(或viewDidAppear)中。

请记住在覆盖时调用超类方法。

答案 1 :(得分:0)

或者,您可以继承UINavigationController并在您感兴趣的事件上发布通知:

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)
    }
}

然后在您的应用程序代表中,您可以观察这些通知:

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
        }