首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在协调器模式中重用ViewController

在协调器模式中重用ViewController
EN

Stack Overflow用户
提问于 2022-07-29 07:57:47
回答 1查看 94关注 0票数 0

我有两个Flow AFlow B协调员。

他们看起来是这样的:

代码语言:javascript
复制
final class HomeCoordinator: Coordinator {

var navigationController: UINavigationController

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

因此,对于每个协调器,我使用一个UINavigationController启动流。

让我们说,流A的协调器需要显示CommonViewController,但是流B的协调器也想显示CommonViewController

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

代码语言:javascript
复制
protocol CommonViewControllerDelegate: AnyObject {
   func showAnotherViewController()
}

class CommonViewController: UIViewController {
   weak var delegate: CommonViewControllerDelegate?

但是使用这种方法,我需要重复代码,因为CoordinatorACorodinatorB都应该实现showAnotherViewController方法。我有这样的多个视图控制器,有时委托不能正常工作,这是一种混乱。

我该如何解决这个问题?我考虑过有一个协调器,但我更愿意将它们分开,这样我就可以为每个协调程序实例化一个UINavigationController

EN

回答 1

Stack Overflow用户

发布于 2022-07-29 10:08:48

我不是斯威夫特人,但试试看。如果希望在类之间共享相同的行为,则可以使用组合或继承。

让我通过继承通过C#展示一个例子:

代码语言:javascript
复制
public class AnotherViewController
{
    public string Show() 
    {
        return "Show AnotherViewController";
    }
}

public class CoordinatorA : AnotherViewController
{
}


public class CorodinatorB : AnotherViewController
{
}

使用作文的实现如下所示:

代码语言:javascript
复制
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();
    }
}

何时选择组合或继承这个话题也值得一读。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73163402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档