我试图了解如何使用 XCoordinator 从子协调器设置根视图控制器。
我有一个运行应用程序协调器的应用程序委托。
我的模式是:
AppDelegate - 应用协调器 --- 主菜单协调器 --- 游戏协调器
(见图)
应用程序协调器不应该直接了解特定的视图控制器,因为我认为视图控制器应该由它们各自的协调器管理。
因此,应用程序协调器应该管理协调器之间的流程并设置一个根初始协调器。
可悲的是,屏幕是空白的,并且一直抱怨我不能“不支持推送导航控制器”。
但是,如果我直接在我的 appcoordinator 中实例化视图控制器,那很好,我不知道为什么。
// AppCoordinator
enum AppRoute: Route {
case mainmenu
case game
}
class AppCoordinator: NavigationCoordinator<AppRoute> {
init() {
super.init(initialRoute: .mainmenu)
}
// MARK: Overrides
override func prepareTransition(for route: AppRoute) -> NavigationTransition {
let router = MainMenuCoordinator().strongRouter
return .push(router)
}
}
这应该启动 MainMenuCoordinator 的初始视图控制器
enum MainMenuRoute: Route {
case mainmenu
}
// MainMenuCoordinator
class MainMenuCoordinator: NavigationCoordinator<MainMenuRoute> {
init() {
super.init(initialRoute: .mainmenu)
}
override func prepareTransition(for route: MainMenuRoute) -> NavigationTransition {
print ("route: \(route as Any)")
let vc = MainMenuViewController.instantiate(.main)
return .push(vc)
}
}
但这会返回一个空白屏幕,并抱怨不支持推送。
但是,如果我移动这段代码:
let vc = MainMenuViewController.instantiate(.main)
return .push(vc)
到 AppCoordinator
像这样:
// MARK: AppCoordinator Overrides
override func prepareTransition(for route: AppRoute) -> NavigationTransition {
let vc = MainMenuViewController.instantiate(.main)
return .push(vc)
}
没关系。出现了一个屏幕——但主菜单协调器不再被“关注”
我想知道 - 你是如何做到的,以便应用程序协调员将责任委托给它的子协调员?
感谢您提供的任何帮助。谢谢
// 编辑:根据提供的答案,我尝试了另一次尝试,将父协调器的引用传递给子协调器。
我希望mainmenucoordinator
使用自己的路线集合;我不想仅仅依赖AppRoutes
.
所以我的应用协调员有这些路线:
enum AppRoute: Route {
case mainmenu
case game
}
class AppCoordinator: NavigationCoordinator<AppRoute> {
init() {
let defaultRoute: AppRoute = .mainmenu
super.init(initialRoute: defaultRoute)
self.rootViewController.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
}
我的主要协调员有以下路线:
enum MainMenuRoute: Route {
case mainmenu
case selectPlayer
case playgame
}
class MainMenuCoordinator: NavigationCoordinator<MainMenuRoute> {
// For my child coordinators, keep a strong reference to parent
private var router: StrongRouter<AppRoute>?
/// ...
}
当我开始初始化它时,我设置了父级。
// MainMenuCoordinator: Init
convenience init(router: StrongRouter<AppRoute>) {
self.init(initialRoute: .mainmenu)
}
但现在它不会使用我为MainMenuCoordinator
;定义的任何路由。相反,它使用AppRoute
例子:
尝试设置路由器MainMenuCoordinator.prepareTransition
override func prepareTransition(for route: MainMenuRoute) -> NavigationTransition {
print ("route: \(route as Any)")
switch route {
case .mainmenu:
let vc = MainMenuViewController.instantiate(.main)
vc.router = strongRouter
return .push(vc)
// ....
}
}
主菜单视图控制器包含对以下内容的引用:
class MainMenuViewController: UIViewController, Storyboarded {
// MARK: - Stored properties
var router: UnownedRouter<MainMenuRoute>!
}
通过这些编辑,根视图控制器现在是白色的;但记录器仍然抱怨我无法推送视图控制器。