斯威夫特弱代表

时间:2018-05-29 20:17:09

标签: ios swift mvvm delegates

我的代码:

public func start() {
    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    guard let listVC = storyboard.instantiateViewController(withIdentifier: "ListVC") as? ListVC else { return }
    let viewModel = ListViewModel(dependencies: appDependencies)
    viewModel.delegate = self
    listVC.listViewModel = viewModel

    navigationController?.pushViewController(listVC, animated: true)
}


protocol ListViewModelDelegate: class {
    func needChangeScreen(cellViewModel: UserCellViewModel)
}

final class ListViewModel {

  weak var delegate: ListViewModelDelegate?

    func userPressed(at index: IndexPath) {
        delegate?.needChangeScreen(cellViewModel: cellViewModels[index.row])
    }
}

从UIViewController调用用户按下,然后我想发送回调给Coordinator来启动另一个协调员但委托?总是零。我知道代表们应该很弱,但在这种情况下不适合我。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Okey我已经修好但我不知道它是不是很好。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let navigationController = UINavigationController()
    navigationController.setNavigationBarHidden(true, animated: false)
    window?.rootViewController = navigationController
    let appDependencies = configureAppDependencies()
    let coordinator = AppCoordinator(navigationController: navigationController, appDependencies: appDependencies)
    coordinator.start()
    window?.makeKeyAndVisible()

    return true
}

这是我的app委托功能(在AppCoordinator启动时创建并推送ListCoordinator)但是当我改变时让let coordinator为实例var:

var coordinator: AppCoordinator?

弱代表不是零,一切正常。