milad sh
milad sh

Reputation: 139

How to initiate a viewcontroller without presenting it?

I have a tab bar controller and a few other viewcontrollers outside the tab bar controller. I have this viewcontroller called "X" which is a part of the tab bar controller. I have another viewcontroller called "Y" which is not a part of the tab bar controller. Now i want to initiate X when im inside Y upon tapping a button without actually presenting it. I want X to become active and fire its viewdidload so that i can access X whenever i chose to do so. Is this possible. Im sorry if im not clear in explaining my quiestion. let me know if you need any other additional information.

Upvotes: 2

Views: 2723

Answers (3)

bluewraith
bluewraith

Reputation: 153

Old question at this point, but I was looking for an answer myself just yesterday and managed to get it figured out.

Instantiate the ViewController, then call loadViewIfNeeded().

Example:

let storyboard = UIStoryboard(name: "Main", bundle: nil) let exampleVC = storyboard.instantiateViewController(withIdentifier: "ExampleViewController") as! ExampleViewController exampleVC.loadViewIfNeeded()

If you want, you can then check if the view is loaded with:

exampleVC.isViewLoaded

The ViewController is now all set up and ready for display when you decide to present it.

Upvotes: 6

Aaron Brager
Aaron Brager

Reputation: 66234

I want X to become active and fire its viewdidload so that i can access X whenever i chose to do so.

UIViewController uses lazy loading for the view property. You can just call:

[myViewController view];

This will trigger the loadView and/or viewDidLoad methods, if implemented.

However, you may wish to consider moving the relevant logic from viewDidLoad to init (or initWithCoder: if using a storyboard/xib). This way you won't have to call -view.

Upvotes: 2

David Bemerguy
David Bemerguy

Reputation: 1364

If I understand right, you want X to be initialised. So you can perform all you initialisation actions on your init constructor. viewDidLoad will only be called by the framework when you perform some presentation, either by pushViewController or addSubview. The reason for that is that because the framework wants to avoid getting instances of views on the memory without being used. So you can initialise all you want from your controllers but the views won't be loaded.

Upvotes: 0

Related Questions