如何在`viewDidLoad`调用

时间:2018-06-07 17:31:14

标签: swift mvvm uiviewcontroller uinavigationcontroller lifecycle

我想在视图控制器调用 viewDidLoad 之前做一些事情。我调用 loadViewIfNeeded(),但 self.navigationController 仍为零。我该如何加载它?

AppDelegate.swift

func someMethod() {
    var viewController = Storyboard.instantiate()
    let viewModel = SomeViewModel()
    vc.bind(to: viewModel)
}

BindableType.swift

protocol BindableType {
    associatedtype ViewModelType

    var viewModel: ViewModelType! { get set }

    func bindViewModel()
}

extension BindableType where Self: UIViewController {
    mutating func bind(to model: Self.ViewModelType) {
        viewModel = model
        loadViewIfNeeded()

        // PROBLEM HERE: navigationController is nil, but view have been loaded
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationController?.navigationItem.largeTitleDisplayMode = .automatic

        bindViewModel()
    }
}

SomeViewController.swift

class SomeViewController: BindableType {

    override func viewDidLoad() {
        super.viewDidLoad()

        // navigationController?.navigationBar.prefersLargeTitles = true
        // navigationController?.navigationItem.largeTitleDisplayMode = .automatic
    }

    func bindViewModel() {
        ...
    }
}

1 个答案:

答案 0 :(得分:0)

我发现了问题。我必须把推动控制器的行放在 viewController.bind(to:viewModel)

之上
double