Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 306
adsurbum Avatar asked Jan 08 '14 20:01

adsurbum


People also ask

Why does viewWillAppear not get called when an app comes back from the background?

The Simple Answer The technical reason for when viewWillAppear gets called is simple. Notifies the view controller that its view is about to be added to a view hierarchy. It can't be any view hierarchy — it has to be the one with a UIWindow at the root (not necessarily the visible window).

How many times is viewWillAppear called?

If both these methods are called, what's the difference between the two? viewDidLoad() is only called once, when the view is loaded from a . storyboard file. viewWillAppear(_:) is called every time the view appears.

Can I call viewWillAppear?

Well, you certainly may call them but Apple says don't. Misusing any method by disregarding Apple's official documentation for the class methods is asking for trouble. If you think you need to send those messages, you're doing something wrong somewhere.

Is viewDidLoad called before viewWillAppear?

viewWillAppear(_:)Always called after viewDidLoad (for obvious reasons, if you think about it), and just before the view appears on the screen to the user, viewWillAppear is called.


2 Answers

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.

like image 173
falsecrypt Avatar answered Oct 11 '22 13:10

falsecrypt


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.

like image 21
gwest7 Avatar answered Oct 11 '22 12:10

gwest7