我想将coordinator模式应用到选项卡栏。
首先,我的AppCoordinator
class AppCoordinator: Coordinator {
let window: UIWindow?
var navigationController: UINavigationController
var childCoordinator: [Coordinator] = []
var parentCoordinator: Coordinator?
init(_ window: UIWindow?, navigationController: UINavigationController) {
self.window = window
self.navigationController = navigationController
window?.makeKeyAndVisible()
}
func start() {
var tabBarController = setTabBarController()
self.window?.rootViewController = tabBarController
}
func setTabBarController() -> UITabBarController {
let tabBar = UITabBarController()
let firstItem = UITabBarItem(title: nil, image: Image.mainImg, tag: 0)
let secondItem = UITabBarItem(title: nil, image: Image.searchImg, tag: 1)
let thirdItem = UITabBarItem(title: nil, image: Image.likePostImg, tag: 2)
let fourItem = UITabBarItem(title: nil, image: Image.profileImg, tag: 3)
let firstCoordinator = MainCoordinator(navigationController: navigationController)
firstCoordinator.parentCoordinator = self
childCoordinator.append(firstCoordinator)
let firstVC = firstCoordinator.startPush()
firstVC.tabBarItem = firstItem
let secondCoordinator = SearchCoordinator(navigationController: navigationController)
secondCoordinator.parentCoordinator = self
childCoordinator.append(secondCoordinator)
let secondVC = secondCoordinator.startPush()
secondVC.tabBarItem = secondItem
let thirdCoordinator = LikePostCoordinator(navigationController: navigationController)
thirdCoordinator.parentCoordinator = self
childCoordinator.append(thirdCoordinator)
let thirdVC = thirdCoordinator.startPush()
thirdVC.tabBarItem = thirdItem
tabBar.viewControllers = [firstVC, secondVC, thirdVC]
return tabBar
}
}
我的MainCoordinator
:
class MainCoordinator: baseCoordinator {
func startPush() -> UINavigationController {
let MainVC = MainViewController(viewModel: .init(coordinator: self))
navigationController.setViewControllers([MainVC], animated: true)
return navigationController
}
}
searchVC
和likePostVC
是相同的。
但是,我的执行结果如下:
为什么我的执行结果是这样的?
2条答案
按热度按时间niwlg2el1#
我认为你需要一个tabBarController的协调器,在这个协调器的开始,你把你的子协调器添加到你的tabBarCoordinator。
登录流程总是在tabBar之前,在启动AppCoordinator时,我初始化登录并将appCoordinator. rootViewController设置为loginCoordinator. rootViewController。
下面是我启动TabBarCoordinator的方法:
下面是如何初始化子协调器:
我试着简化代码,这可能不是你要找的直接答案,但我认为这将有助于理解模式。}
mrzz3bfm2#
我看到两个问题:
1.使parentConordinator为
weak
以防止保留循环1.你正在传递相同的navigationController到你所有的标签根目录。2这不起作用,可能就是你所看到的问题的原因。