使用协调器模式在控制器之间传递数据

Passing data in between controllers using coordinator pattern

我正在尝试了解协调器模式的工作原理。

这是我的代码

import UIKit
import Foundation

class CheckoutCoordinator: Coordinator, ScheduleDelegate {
    
    var childCoordinator: [Coordinator] = [Coordinator]()
    var navigationController: UINavigationController
    
    init(nav: UINavigationController) {
        self.navigationController = nav
    }
    
    func start()  {
        let ctrl = CheckoutController.initFromStoryboard()
        ctrl.coordinator = self
        self.navigationController.pushViewController(ctrl, animated: true)
    }
    
    func openSchedule()  {
        let ctrl = ScheduleController.initFromStoryboard()
        ctrl.delegate = self
        self.navigationController.pushViewController(ScheduleController.initFromStoryboard(), animated: true)
    }
    
    func didSelectTimings(date: NSDate, timings: NSString, distance: Double) {
        
    }

}

CheckoutController,我转到 ScheduleController,做一些调用其委托方法的工作。委托应该更新 CheckoutController 和 pop scheduleController 中的一些值。我无法找到上述 senario 的任何具体解释以及如何“正确”实施它。

请注意,调度控制器没有向前导航,因此没有协调器 class。

任何指导将不胜感激

我不会在协调器中处理委托逻辑。相反,我会把它直接移到您的 CheckoutController 中。所以当调用 ScheduleController 时,它会在你的协调器中看起来像这样:

func openSchedule(delegate: ScheduleDelegate?)  {
    let ctrl = ScheduleController.initFromStoryboard()
    ctrl.delegate = delegate
    navigationController.pushViewController(ScheduleController.initFromStoryboard(), animated: true)
}

并且在你的 CheckoutController 中,符合 ScheduleDelegate 委托:

class CheckoutController: ScheduleDelegate {
    func didSelectTimings(date: NSDate, timings: NSString, distance: Double) {
       // Do your staff   
    }
}

然后在您的 ScheduleController 中调用委托方法后,我将调用协调器弹出自身(在这种情况下 ScheduleController)。

delegate?.didSelectTimings(date: yourDate, timings: someTiming, distance: distance)
if let checkoutCoordinator = coordinator as? CheckoutCoordinator {
       checkoutCoordinator.popViewController() 
}

弹出逻辑可以单独在您的 viewController 中,但我喜欢只在 Coordinator 中保留导航。在你的 CheckoutCoordinator 中,或者在你的 Coordinator 中更好(因为这个函数非常通用),实现 pop 函数。

extension Coordinator {
     function popViewController(animated: Bool = true) {
         navigationController?.popViewController(animated: animated)
     }
}