Reputation: 469
I have two coordinators for Flow A
and Flow B
.
They look like this:
final class HomeCoordinator: Coordinator {
var navigationController: UINavigationController
init(navigationController: UINavigationController = UINavigationController()) {
self.navigationController = navigationController
So for each coordinator I start the flow with an UINavigationController
.
Let's say that coordinator with Flow A needs to display CommonViewController
, but the coordinator with Flow B would also like to show the CommonViewController
.
Since the coordinator is injected in CommonViewController
, it can't be both CoordinatorA
or CoordinatorB
. So to perform coordinator operations I've added a delegate that looks like this:
protocol CommonViewControllerDelegate: AnyObject {
func showAnotherViewController()
}
class CommonViewController: UIViewController {
weak var delegate: CommonViewControllerDelegate?
But with this approach I have duplication of code because both CoordinatorA
and CorodinatorB
should implement showAnotherViewController
method. And I have multiple view controllers like this, sometimes the delegate doesn't work properly and it's a chaos.
How can I solve this problem? I thought about having one coordinator, but I prefer to keep them separate so I can instantiate one UINavigationController
per Coordinator.
Upvotes: 1
Views: 297
Reputation: 38199
I am not Swift guy, but give me a try. If you want to share the same behaviour between classes, then you can use composition or inheritance.
Let me show an example of inheritance via C#:
public class AnotherViewController
{
public string Show()
{
return "Show AnotherViewController";
}
}
public class CoordinatorA : AnotherViewController
{
}
public class CorodinatorB : AnotherViewController
{
}
and an implementation with composition would look like this:
public class AnotherViewController
{
public string Show()
{
return "Show AnotherViewController";
}
}
public class CoordinatorA
{
private AnotherViewController _anotherViewController;
public CoordinatorA()
{
_anotherViewController = new AnotherViewController();
}
}
public class CorodinatorB
{
private AnotherViewController _anotherViewController;
public CorodinatorB()
{
_anotherViewController = new AnotherViewController();
}
}
It is worth to read also this topic when to choose composiiton or inheritance.
Upvotes: 1