objective-cxcode4.5

How to check if a view is inViewHierarchy or not?


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?


Solution

  • 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
    }