我有一个应用程序,其中UI是以编程方式设置的,而不是使用Storyboards。我纠结于如何知道何时切换了标签。。。当它被切换后,我希望能够在每个视图控制器中分配一个名为"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中的userSetting。userSettings是我的应用程序中的一个中心对象,我没有创建一个singleton,而是试图通过将对该对象的引用传递给其他视图控制器来让应用程序工作。
我不确定这是否可以通过检测选项卡何时切换并传递值来实现,或者我是否需要使用委托模式?
我怎样才能做到这一点?我尽量避免使用单身汉。
您可以通过以下6种方式在视图控制器之间传递数据:
Instance
属性(A→B(Segues
(用于情节提要(Instance
的性质和函数(A←B(Delegation
模式-您可以尝试委托模式,这将是我的第一个最佳选择Closure
或completion handler
NotificationCenter
和Observer
模式-在您的情况下,这将是第二好的选择