How do I check if an UIViewController is currently

2019-04-04 06:54发布

How do I check if an UIViewController is currently being displayed?

My UIViewControllers are listening for NSNotifications - even if when they are not displayed (ie not shown). So I could have 10 UIViewController in the background observing NSNotifications from NSNotificationCenter. When an NSNotification is posted and received by the UIViewController, I'd like to find out if it is currently being shown. If it is not, I will just set a boolean so that it will processed when the View is presented. If it currently being display, I will do more things like update tables immediately, and so forth...

6条回答
再贱就再见
2楼-- · 2019-04-04 07:09

You can use flags in viewWillAppear and viewWillDisappear methods for this.

查看更多
手持菜刀,她持情操
3楼-- · 2019-04-04 07:10

You need to check if your viewcontroller is on top of the stack of navigationcontroller's viewcontroller array. A sample code is,

if (self.navigationController.topViewController == self) {
    //the view is currently displayed
}

You can use this inside the viewWillAppear method to check whether the current view is visible.

查看更多
【Aperson】
4楼-- · 2019-04-04 07:29

Check to see if it's attached to the window. If it's not nil it's in hierarchy which is attached to the screen (of course it could be off the bounds of the screen, covered by some other view or have the hidden flag set)

if (myViewController.view.window) {
  // I'm attached to the window
} else {
  // not attached to the window
}
查看更多
Animai°情兽
5楼-- · 2019-04-04 07:30

I think that checking of viewController.view.superview should works.

查看更多
仙女界的扛把子
6楼-- · 2019-04-04 07:34

Why don't you remove the notification listener in viewWillDisappear and add it in viewWillAppear?

Edit: misread his question, sorry.

Suggested answer: set your own flag (BOOL) in viewDidDisappear and viewDidAppear.

查看更多
放荡不羁爱自由
7楼-- · 2019-04-04 07:36

Specify title to each ViewController and then get the title of current ViewController by the code given bellow.

NSString *currentController = self.navigationController.visibleViewController.title;

Then check it by your title like this

if([currentController isEqualToString:@"myViewControllerTitle"]){

    //write your code according to View controller. 

}
查看更多
登录 后发表回答