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

wwwo4jvm  于 2023-03-14  发布在  iOS
关注(0)|答案(1)|浏览(144)

我试图理解协调模式的工作原理。
下面是我的代码:

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中的一些值并弹出scheduleController。我找不到任何具体的解释,以及如何“正确”地实现它。
注意,调度控制器没有向前导航,因此没有协调器类。

mum43rcc

mum43rcc1#

我不会在协调器中处理委托逻辑,而是将它直接移到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中调用delegate方法后,调用协调器弹出self(在这种情况下为ScheduleController)。

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

弹出逻辑可以只在viewController中,但我喜欢只在Coordinator中进行导航。在CheckoutCoordinator中,或者更好的是在Coordinator中(因为这个函数非常通用),实现弹出函数。

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

相关问题