我试图执行一个函数,每次应用程序加载一个新的ViewController(过渡到不同的视图)。为了避免在每个ViewController中调用这个函数(大约有10个ViewController,还有更多要添加),我希望在AppDelegate中通过添加某种观察者来做到这一点。这可能吗?或者它能以某种方式与UIViewController扩展的帮助?
或者你可以子类化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
}
忘记AppDelegate, observer或extensions,使用Inheritance。
你所有的uiviewcontroller应该扩展MainViewController基类,你可以把你的逻辑在基类的viewDidLoad方法(或viewDidAppear)。