【问题标题】:Passing data in between controllers using coordinator pattern使用协调器模式在控制器之间传递数据
【发布时间】:2021-02-25 10:44:27
【问题描述】:

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

这是我的代码

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 的任何具体解释以及如何“正确”实施它。

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

任何指导将不胜感激

【问题讨论】:

    标签: ios swift xcode coordinator


    【解决方案1】:

    我不会在协调器中处理委托逻辑。相反,我会将其直接移至您的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)
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 2011-07-09
      相关资源
      最近更新 更多