iOS how to detect programmatically when top view controller is popped?

后端 未结 10 1295
逝去的感伤
逝去的感伤 2020-12-04 17:32

Suppose I have a nav controller stack with 2 view controllers: VC2 is on top and VC1 is underneath. Is there code I can include in VC1 that will detect that VC2 has just be

相关标签:
10条回答
  • 2020-12-04 18:21

    One way you could approach this would be to declare a delegate protocol for VC2 something like this:

    in VC1.h

    @interface VC1 : UIViewController <VC2Delegate> {
    ...
    }
    

    in VC1.m

    -(void)showVC2 {
        VC2 *vc2 = [[VC2 alloc] init];
        vc2.delegate = self;
        [self.navigationController pushViewController:vc2 animated:YES];
    }
    
    -(void)VC2DidPop {
        // Do whatever in response to VC2 being popped off the nav controller
    }
    

    in VC2.h

    @protocol VC2Delegate <NSObject>
    -(void)VC2DidPop;
    @end
    
    @interface VC2 : UIViewController {
    
        id<VC2Delegate> delegate;
    }
    
    @property (nonatomic, assign) id delegate;
    
    ...
    
    @end
    

    VC2.m

    -(void)viewDidUnload {
        [super viewDidUnload];
        [self.delegate VC2DidPop];
    }
    

    There's a good article on the basics of protocols and delegates here.

    0 讨论(0)
  • 2020-12-04 18:22

    You can also detect in the view controller that is being popped

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    
        if ([self isMovingFromParentViewController]) {
            ....
        }
    }
    
    0 讨论(0)
  • 2020-12-04 18:23

    You can add an observer for NSNotification specifically JUST for your VC2.

    // pasing the "VC2" here will tell the notification to only listen for notification from
    // VC2 rather than every single other objects
    [[NSNotitificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) object:VC2];
    

    Now in in your VC2's view will disappear, you can post a notification:

    -(void)viewWillDisappear
    {
        [[NSNotificationCenter defaultCenter] postNotificationNamed:@"notif_dismissingVC2" object:nil];
    }
    
    0 讨论(0)
  • 2020-12-04 18:25

    This is worked for me

    UIViewController *fromViewController = [[[self navigationController] transitionCoordinator] viewControllerForKey:UITransitionContextFromViewControllerKey];
    if (![[self.navigationController viewControllers] containsObject:fromViewController] && !self.presentedViewController)
    {
      //Something is being popped and we are being revealed 
    }
    
    0 讨论(0)
提交回复
热议问题