How do I know if a view is visible or not?

2019-09-08 02:36发布

Say I have two view controllers: xVC and yVC. I have used the shake API and and have used the methods -(void)motionBegan,-(void)motionEnded: and -(void)motionCancelled in xVC. What happens is when the device is shaken, it fires a simple animation. Now the thing is that this animation is fired even when the I have yVC open that is, when yVS.view has been added as the subview. What I am looking for is some if condition which I can use in -(void)motionEnded: like this:

if(yVC == nil)
{
     //trigger animation
} 

By that I mean that the shake shouldn't work when yVC is visible. How do I do that? Please help.

3条回答
The star\"
2楼-- · 2019-09-08 03:07

The previous answers all work to some degree, but fail to take modally presented view controllers into account. If view controller A presents view controller B, of the previous answers will tell you that A is still visible. If you, like me, want to know whether or not the view is actually visible (and not just a part of the view hierarchy), I would suggest also checking the presentedViewController property:

if (self.isViewLoaded && [self.view window] && !self.presentedViewController) {
    // User is looking at this view and nothing else
}

This works since presentedViewController will be non-nil whenever the current view controller OR any of its ancestors are currently presenting another view controller.

查看更多
手持菜刀,她持情操
3楼-- · 2019-09-08 03:14

Add this to both of your view controllers:

-(void)viewDidAppear:(BOOL)animated 
{
  [super viewDidAppear:animated];    
  visible = YES;    
}

-(void)viewDidDisappear:(BOOL)animated 
{
  [super viewDidDisappear:animated];
  visible = NO;
}

Now, just check the variable isVisible of both the view controllers and trigger your animation likewise.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-09-08 03:25

The general advice I have seen and used is to ask a view if it has a non-nil window property:

if( ! yVC.view.window) {
  // trigger animation
}

But note that this doesn't always equate with being visible; though in most apps it's about as good as you can performantly get (the basic case where it's not accurate is when a different view completely obscures it, but this may still satisfy your needs)

查看更多
登录 后发表回答