Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loadViewIfNeeded before iOS 9

I need to create and load a UIViewController before inserting it as a subview into another UIViewController.

In iOS 9 I could do myController.loadViewIfNeeded(). What is a good workaround for iOS 8?

It seems that myController.view.hidden = myController.view.hidden works but it seems like a dangerous hack.

like image 753
Code Avatar asked Feb 06 '16 09:02

Code


1 Answers

There are many ways in which you can force view controller to load its view. In fact, the most common way (as far as I know) is to access view property of the view controller.

_ = viewController.view

I wouldn't treat this as a hack. In fact, Apple's documentation states that accessing the view property when it is equal to nil results in loading the requested view. This means that proposed solution is safe and should work as intended even with future releases of the iOS. From Apple's documentation:

The view stored in this property represents the root view for the view controller's view hierarchy. The default value of this property is nil.

If you access this property and its value is currently nil, the view controller automatically calls the loadView method and returns the resulting view.

like image 128
Rafał Augustyniak Avatar answered Oct 09 '22 12:10

Rafał Augustyniak