繁体   English   中英

在协调器模式中重用 ViewController,Swift

[英]Reuse ViewController in Coordinator pattern, Swift

我有两个协调员Flow AFlow B

它们看起来像这样:

final class HomeCoordinator: Coordinator {

var navigationController: UINavigationController

init(navigationController: UINavigationController = UINavigationController()) {
    self.navigationController = navigationController

因此,对于每个协调员,我从UINavigationController开始流程。

假设流 A 的协调器需要显示CommonViewController ,但流 B 的协调器也想显示CommonViewController

由于协调器是在CommonViewController中注入的,因此它不能同时是CoordinatorACoordinatorB 因此,为了执行协调器操作,我添加了一个如下所示的委托:

protocol CommonViewControllerDelegate: AnyObject {
   func showAnotherViewController()
}

class CommonViewController: UIViewController {
   weak var delegate: CommonViewControllerDelegate?

但是使用这种方法我有重复的代码,因为CoordinatorAshowAnotherViewController CorodinatorB 而且我有多个这样的视图控制器,有时委托不能正常工作,而且很混乱。

我怎么解决这个问题? 我曾想过拥有一个协调器,但我更喜欢将它们分开,这样我就可以为每个协调器实例化一个UINavigationController

我不是 Swift 家伙,但请尝试一下。 如果要在类之间共享相同的行为,则可以使用组合或 inheritance。

让我通过 C# 展示inheritance的示例:

public class AnotherViewController
{
    public string Show() 
    {
        return "Show AnotherViewController";
    }
}

public class CoordinatorA : AnotherViewController
{
}


public class CorodinatorB : AnotherViewController
{
}

组合的实现看起来像这样:

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();
    }
}

还值得阅读该主题何时选择Composiiton或inheritance

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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