简体   繁体   中英

Reuse ViewController in Coordinator pattern, Swift

I have two coordinators for Flow A and Flow B .

They looks 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 .

Lets 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM