我怎么知道切换标签页的时间?

问题描述 投票:0回答:1

我有一个可以通过编程方式而不是使用Storyboard来设置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是我的应用程序中的中心对象,而不是创建单例,而是通过将对对象的引用传递给其他视图控制器来使该应用程序正常工作。

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

我该如何完成?我试图避免使用单例。

ios swift delegates appdelegate
1个回答
0
投票

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

  1. 实例属性(A→B)
  2. [Segues(用于情节提要)] >>
  3. [Instance属性和函数(A←B)
  4. Delegation模式
  5. [Closurecompletion handler
  6. [NotificationCenterObserver模式-我认为这将是您的最佳选择。
© www.soinside.com 2019 - 2024. All rights reserved.