My practice of applying coordinator pattern in an iOS project
- App coordinator
- Main coordinator
- Other child coordinators
Usually, nagivation includes
- using navigation controller to push a view controller to its child view controllers stack
- preseting another view controller
So bedisde Coordinator protocol, I make PresentingCoordinator and NavigationCoordinator too. They both conform to Coordinator protocol but have their own navigation functions.
Also, to make things easier, I made three base classes
- class BasePresentingCoordinator: PresentingCoordinator
- class BaseNavigationCoordinator: NavigationCoordinator
- class BaseVersatileCoordinator: VersatileCoordinator (VersatileCoordinator:PresentingCoordinator, NavigationCoordinator)
For a child coordinator, if the view controller it manages is being pushed by a navigation controller, choose NavigationCoordinator as its parent class and use navigate(:::) to show the view controller.
if the view controller it manages is being presented, choose PresentingCoordinator as its parent class and use present(:::) to show the view controller.
If the view controller can be pushed and presented, then use BaseVersatileCoordinator as its parent class.
Implementing a BackwardConscious protocol to make a view controller to know then it is being pushed back or dismissed.
use initial functions
- Make the view controller conforms BackwardConscious protocol
- Implement getPassingInfo()
- Set removeChildHandler inside the coordinator
removeChildHandler = { [weak vc] child, info in
if child is OperationCoordinator, let result = info?["result"] as? Int {
vc?.setResult(result)
return
}
if child is SettingsCoordinator, let number = info?["initialNumber"] as? Int {
vc?.setInitialNumber(number)
return
}
}