我怎么知道标签何时被切换?

How can I know when a tab was switched?

我有一个应用程序,其中 UI 是通过编程方式设置的,而不是使用故事板。我被困在如何知道选项卡何时被切换......以及何时切换我希望能够在每个视图控制器中分配一个名为 "userSettings" 的 属性 以便我可以通过这个对象并适当地调用它的方法。

这是我的应用委托:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var contentVC: BMContentViewController?
    var settingsVC: BMSettingsViewController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        contentVC = BMContentViewController()
        contentVC?.view.backgroundColor = .clear
        contentVC?.tabBarItem.title = "Content"

        settingsVC = BMSettingsViewController()
        settingsVC?.view.backgroundColor = .clear
        settingsVC?.tabBarItem.title = "Settings"

        let tabbarController = UITabBarController()
        tabbarController.viewControllers = [(contentVC ?? UIViewController()), settingsVC ?? UIViewController()]

        self.window?.rootViewController = tabbarController
        self.window?.makeKeyAndVisible()

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {}
    func applicationDidEnterBackground(_ application: UIApplication) {}
    func applicationWillEnterForeground(_ application: UIApplication) {}
    func applicationDidBecomeActive(_ application: UIApplication) {}
}

BMContentViewController() 和 BMSettingsViewController() 每个都有一个 属性 调用:

var userSettings: BMUserSettings?

我在 BMContentViewController() 中启动应用程序。当我切换选项卡时,我希望能够将 BMSettingsViewController() 中的 userSettings 分配给 BMContentViewController() 中的 userSettings。 userSettings 是我的应用程序中的一个中心对象,而不是创建一个单例,我试图通过将对该对象的引用传递给其他视图控制器来使该应用程序工作。

我不确定这是否可以通过检测选项卡何时切换并传递值来实现,或者我是否需要改用委托模式?

我怎样才能做到这一点?我试图避免使用单例。

您可以通过 6 种方式在视图控制器之间传递数据:

  1. Instance 属性 (A → B)
  2. Segues(对于故事板)
  3. Instance 属性和函数 (A ← B)
  4. Delegation 模式 - 你可以尝试委托模式,这将是我的第一个最佳选择
  5. Closurecompletion handler
  6. NotificationCenterObserver 模式 - 这将是您的第二个最佳选择。