Force viewDidLoad to fire on iOS

2019-01-22 19:51发布

问题:

I have two window app and while I present first window I would like the view in second window to load and prepare content for later in background.

I've tried to use method loadView but Apple says you should not call this method directly.

So far I've chosen to use the view's method userInteractionEnabled which actually implicitly calls viewDidLoad method.

Is there an elegant way to force ViewControllers viewDidLoad method to fire before it should naturally (when window is key and presented)?

回答1:

You can just call [viewController view];.

The documentation for UIViewController explains how the view property is lazy-loaded and that viewDidLoad is called after the view is loaded.



回答2:

In iOS 9, Apple finally fixed this:

// Loads the view controller's view if it has not already been set.
@available(iOS 9.0, *)
public func loadViewIfNeeded()


回答3:

Swift 2.0, with same result of @Carl Veazey's solution:

let viewController = MyCustomViewController()
_ = viewController.view


回答4:

You can create a global instance for that controller(May be in AppDelegate) and call the method you want to perform the action for. Then While pushing to that controller don't create a new instance Just use the instance you have created for global use.