swift - 如何在调用 `viewDidLoad` 之前加载 self.navigationController

标签 swift mvvm uiviewcontroller uinavigationcontroller lifecycle

我想在 View Controller 调用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() {
        ...
    }
}

最佳答案

我发现了问题。我必须将带有推送 Controller 的行放在 viewController.bind(to: viewModel)

之上
self.navigationViewController.pushViewController(viewController, animated: true)
viewController.bind(to: viewModel)

关于swift - 如何在调用 `viewDidLoad` 之前加载 self.navigationController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747085/

相关文章:

ios - fatal error : use of unimplemented initializer 'init(size:)' for class

ios - swift Realm 列表<T> 未填充

c# - Wpf Datagrid将选定值与值路径绑定(bind)

objective-c - 如何使用 PKRevealController 切换 Front View Controller?

iphone - AQGridView - ExpanderDemo 中的方向更改

swift - RxSwift/RxCocoa : prevent UITextField from having more than . .. 字符

swift - 如何将一个值与多个值进行比较 - Swift

c# - 为 ListViewItem 执行命令的附加行为

ios - ViewModel 能否返回其他 ViewModel

ios - 从 UISplitViewController 的详细信息 View Controller 导航到正常的全尺寸 UIViewController