代码组织框架

一、一般的目录结构

VC:ViewControllers
VM:ViewModels
Coordinator:大门
Controller:控制器/管理器

二、Coordinator总协议

每个Coordinator必须继承的protocol

protocol Coordinator: class {
    var coordinators: [Coordinator] { get set }
}

extension Coordinator {
    func addCoordinator(_ coordinator: Coordinator) {
        coordinators.append(coordinator)
    }

    func removeCoordinator(_ coordinator: Coordinator) {
        coordinators = coordinators.filter { $0 !== coordinator }
    }

    func removeAllCoordinators() {
        coordinators.removeAll()
    }
}

三、实现模块Coordinator

  1. 继承Coordinator
final class SettingsCoordinator: Coordinator {
    ...
  //创建对应的VC
    lazy var rootViewController: SettingsViewController = {
        let controller = SettingsViewController(
            session: session,
            keystore: keystore
        )
        controller.delegate = self
        controller.modalPresentationStyle = .pageSheet
        return controller
    }()

  //构造方法
    init(
        navigationController: NavigationController = NavigationController()
    ) {
        self.navigationController = navigationController
        self.navigationController.modalPresentationStyle = .formSheet
    }

  //start
    func start() {
        navigationController.viewControllers = [rootViewController]
    }
   //Coordinator自己也要接收来自内部ViewController的回调:
  //就是上面构造时的
    controller.delegate = self

//一会也有对应的delegate,用于返回coordinator的返回值,如:

protocol SettingsCoordinatorDelegate: class {
    func didRestart(with account: WalletInfo, in coordinator: SettingsCoordinator)
    func didPressURL(_ url: URL, in coordinator: SettingsCoordinator)
    func didCancel(in coordinator: SettingsCoordinator)
}

四、Coordinator模块间相互调用

比如要调用钱包Coordinator

    private func showWallets() {
        let coordinator = WalletsCoordinator(keystore: keystore, navigationController: navigationController)
        coordinator.delegate = self
        navigationController.pushCoordinator(coordinator: coordinator, animated: true)
    }

你可能感兴趣的:(代码组织框架)