Force viewDidLoad to fire on iOS
Asked Answered
D

4

28

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)?

Demurral answered 3/10, 2012 at 7:21 Comment(0)
R
58

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.

Redcoat answered 3/10, 2012 at 7:25 Comment(4)
So simple yet so powerful :) Thanks!Demurral
Nice! At first I tried viewController.view but it gave a warning but sending it the message "view" this way doesn't give a warning at allAlrich
This was exactly what I was looking for, but is there a documentation/explanation on how this works and what it does?Novation
@Novation Yes the documentation for UIViewController explains how the view property is lazy-loaded and that viewDidLoad is called after the view is loaded.Redcoat
M
35

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()
Masqat answered 21/7, 2016 at 7:53 Comment(1)
Here is the real answerHyetal
A
6

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

let viewController = MyCustomViewController()
_ = viewController.view
Attorneyatlaw answered 20/1, 2016 at 0:27 Comment(5)
I am trying this with swift and it's not working... Did this stop working with the newer versions of iOS/Swift?Furlana
What do you mean with "newer versions of iOS/Swift"? Swift 3.0? I didn't test Swift 3.0 yet, so I don't know If this approach still works.Ables
I am using swift 2.2, and this is not working for me... The only difference between my code and yours is that instead of instatiating the View Controller myself, I am calling the method instantiateViewControllerWithIdentifier of the storyboard instance.Furlana
My bad, I was instantiating a NavigationController, that's why it wasn't working... Thank youFurlana
Ok, no problem. I've just test and confirm that It still works! ;)Ables
S
0

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.

Sverre answered 3/10, 2012 at 7:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.