13

For example, if a view of a viewController is in viewHierarchy and I just finished downloading stuff, I want to update stuff quickly. If self.view is not in viewHierarchy, I want to postpone updating.

I suppose, I can just add a boolean variable to indicate that and put it on viewWillAppear and viewWillDisappear.

I can also scan windows and see if UIView is in the viewHierarchy or not.

Is there a more straightforward way?

user4234
  • 1,523
  • 1
  • 20
  • 37

3 Answers3

25

As of iOS 9.0, in Swift, you can do this in your view controller:

if viewIfLoaded?.window != nil {
    // view should be updated
}

or this if you want to actually use the view:

if let view = viewIfLoaded, view.window != nil {
    // update view
}

For older versions of iOS, in Objective-C:

if (self.isViewLoaded && self.view.window != nil) {
    // view is in a view hierarchy and should be updated
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • if checking isViewLoaded necessary? Given that self.view.window must be nil anyway if view is not loaded. Also the view is loaded the first time you access the self.view right? – user4234 Dec 05 '12 at 04:15
  • Yes, the view will be loaded when you call `self.view`, if it's not already loaded. If the view hasn't been loaded yet, then it's definitely not on screen. If it's not on screen, you want to postpone updating. If you're going to postpone updating, why load the view? – rob mayoff Dec 05 '12 at 04:37
  • we can use `self.viewIfLoaded.window` after iOS 9 https://stackoverflow.com/a/2777460 – tomtclai Sep 30 '20 at 22:03
1

viewDidLoad will get triggered only after the view loading is done, i think. So you can add necessary functionality in viewDidLoad itself, i think.

Paramasivan Samuttiram
  • 3,728
  • 1
  • 24
  • 28
-2

To check if it's not in the view hierarchy, this is enough:

// From a UIViewController sub-class
if !self.isViewLoaded {
    // view is not in the view hierarchy
}
Jonathan Cabrera
  • 1,656
  • 1
  • 19
  • 20
  • 1
    That's not correct. It is possible that the view has been loaded, but hasn't been added to the view hierarchy yet (For example, right after you access `self.view` in a `UIViewController`'s initializer). – Theo Jul 02 '19 at 17:32