繁体   English   中英

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

[英]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 ,我 go 到ScheduleController ,做一些调用其委托方法的工作。 委托应该更新 CheckoutController 和 pop scheduleController 中的一些值。 我无法找到上述 senario 的任何具体解释以及如何“正确”实施它。

请注意,时间表 controller 没有向前导航,因此没有协调器 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中,我会调用协调器来弹出 self(在这种情况下为ScheduleController )。

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

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

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

暂无
暂无

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

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