IOS determine whether UIViewController currently being displayed

My usual approach is based on life-cycle view controller to determine whether it is a state of being used. 

Examples instance a Boolean variable set in -ViewWillAppear isVisible inside isVisible = YES; -ViewWillDisappear in which isVisible = NO; and when required by the method of embodiment

Recently a colleague shared a clever method is as follows: http: //edsioon.me/if-uiviewcontroller-is-display/

 
   

Determining whether UIViewController is being displayed

 
    
   
 
   

In some cases, the need to determine whether the ViewController currently being displayed, such as background network request error, we may only want to prompt the user to a page pop initiated the request, when the user has to jump to another interface, not pop, reducing the user interference.

If a UIView object that is currently displayed, then it's definitely a non-null value of the properties window. While official document to explain UIView property value when the window is not displayed, but after a simple test, in most cases UIView is not displayed, the window is empty, according to this judgment whether UIViewController currently being displayed. However, when accessing the UIViewController view properties, it may cause view is loaded (if this time is not yet loaded), it is unnecessary, but also may cause unexpected problems. Therefore, before accessing the properties view, it is best to check isViewLoaded property to avoid these problems.

The sample code below, the method declares a isVisible extended in UIViewController for later calls

Whether UIViewController is being displayed

 

Note: The official documentation of UIView only indicate when a view has not been added to the window, window properties are empty; but did not mention when the window is nil, the current view is not displayed. Demo detected by a simple method described above can meet most needs, it is recommended that the use of a simple test!

Haha instantly feel so low, but be aware that this method is practical conditions under Oh !!! view controller is not a special case, in general can be used.

I wrote a class method is more convenient to call haha

as follows:

+(BOOL)isCurrentViewControllerVisible:(UIViewController *)viewController
{
    return (viewController.isViewLoaded && viewController.view.window);
}

I want to be judged according to distinguish between life-cycle view of the tall and methods on which comparison is to compare it? The answer tomorrow

Reproduced in: https: //www.cnblogs.com/someonelikeyou/p/4331286.html

Guess you like

Origin blog.csdn.net/weixin_33691598/article/details/94538133