Can i know in viewWillAppear that it was called after navigationController pop (back button)?

会有一股神秘感。 提交于 2019-12-03 14:47:04

问题


Say I have UIViewController A and B. User navigates from A to B with a push segue. Than user presses back button and comes to A.

Now viewWillAppear of A is called. Can I know in the code here that I came from back button (navigationController popTo...) and not by another way? And without writing special code in the B view controller.


回答1:


hm, maybe you can use self.isMovingToParentViewController in viewWillAppear, see docs, if it is NO then it means the current view controller is already on the navigation stack.




回答2:


I like to do the following in view controller A:

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if (_popping) {
        _popping = false;
        NSLog(@"BECAUSE OF POPPING");
    } else {
        NSLog(@"APPEARING ANOTHER WAY");
    }

    //keep stack size updated
    _stackSize = self.navigationController.viewControllers.count;

    ....
}
- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    _popping = self.navigationController.viewControllers.count > _stackSize;

    ....
}

What you are doing is keeping track of whether your view controller (A) is disappearing because a view controller (B) is being pushed or for another reason. Then (if you did not modify the child view controller order) it should accurately tell you if (A) is appearing because of a pop on the navigation controller.




回答3:


Add a BOOL property to UIViewController A:

@property (nonatomic) BOOL alreadyAppeared;

Then in your viewWillAppear: method, add:

if (!self.alreadyAppeared) {
    self.alreadyAppeared = YES;
    // Do here the stuff you wanted to do on first appear
}


来源:https://stackoverflow.com/questions/21005846/can-i-know-in-viewwillappear-that-it-was-called-after-navigationcontroller-pop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!