Code
Code

Reputation: 6251

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.

Upvotes: 6

Views: 2677

Answers (1)

Rafał Augustyniak
Rafał Augustyniak

Reputation: 2031

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.

Upvotes: 11

Related Questions