我有一个可以通过编程方式而不是使用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是我的应用程序中的中心对象,而不是创建单例,而是通过将对对象的引用传递给其他视图控制器来使该应用程序正常工作。
我不确定是否可以通过检测何时切换选项卡并传递值或是否需要使用委托模式来实现?
我该如何完成?我试图避免使用单例。
您可以通过6种方式在视图控制器之间传递数据:
Segues
(用于情节提要)] >>Instance
属性和函数(A←B)Delegation
模式Closure
或completion handler
NotificationCenter
和Observer
模式-我认为这将是您的最佳选择。