How to check if a view is inViewHierarchy or not?
Asked Answered
E

3

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?

Enugu answered 5/12, 2012 at 2:38 Comment(0)
L
27

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
}
Lob answered 5/12, 2012 at 2:48 Comment(3)
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?Enugu
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?Lob
we can use self.viewIfLoaded.window after iOS 9 stackoverflow.com/a/2777460Isometropia
E
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.

Enrich answered 5/12, 2012 at 3:5 Comment(0)
R
-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
}
Rainproof answered 5/12, 2018 at 15:15 Comment(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).Scurvy

© 2022 - 2024 — McMap. All rights reserved.