【问题标题】:Detect UIViewController change from AppDelegate从 AppDelegate 检测 UIViewController 的变化
【发布时间】:2017-03-16 23:09:30
【问题描述】:

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

【问题讨论】:

    标签: ios swift uiviewcontroller appdelegate


    【解决方案1】:

    或者,您可以继承 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)
        }
    }
    

    然后在您的 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
            }
    

    【讨论】:

      【解决方案2】:

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

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

      重写时记得调用超类方法。

      【讨论】:

      • 这是否意味着我必须对每个 ViewController 进行子类化?
      • 是的,你应该这样做。代码集中化通常是避免重复代码和编写更具可扩展性的程序的正确方法
      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多