118

I've read numerous posts about people having problems with viewWillAppear when you do not create your view hierarchy just right. My problem is I can't figure out what that means.

If I create a RootViewController and call addSubView on that controller, I would expect the added view(s) to be wired up for viewWillAppear events.

Does anyone have an example of a complex programmatic view hierarchy that successfully receives viewWillAppear events at every level?

Apple's Docs state:

Warning: If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly. Failing to send the view controller this message will prevent any associated animation from being displayed.

The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view?

I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
chzk
  • 1,199
  • 2
  • 8
  • 3
  • I had this problem until I realized that I was mis-understanding the intended use of UIViewController subclasses generally. Check out this Question. http://stackoverflow.com/questions/5691226/am-i-abusing-uiviewcontroller-subclassing/5691708#comment-6507338 – averydev Apr 17 '11 at 23:26
  • 7
    Please beware!!! No longer true on iOS 5 !!! Calls viewWillAppear and viewDidAppear automatically – Vilém Kurz Nov 10 '11 at 17:23
  • For anyone coming here today and developing for iOS 13+, scroll down to Bilal's answer which speaks to this specifically – forresthopkinsa Apr 23 '21 at 17:57

27 Answers27

56

If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked.

You need to use the navigation controller delegate methods instead:

navigationController:willShowViewController:animated:
navigationController:didShowViewController:animated:
mmalc
  • 8,201
  • 3
  • 39
  • 39
  • 2
    I hadn't set my navigation controller's delegate and still the method was not getting called. Anyway, I set it and then I used the methods you mention above. Thanks. – Dimitris Mar 29 '10 at 12:53
  • I'm seeing the same thing as Dimitris – jkp Apr 14 '11 at 08:15
  • 7
    I just tested this in iOS4 and iOS5: This is NOT true: Setting the delegate of a navigationController and then pushing a view to it WILL fire viewWillAppear: etc. – DaGaMs Nov 07 '11 at 13:44
  • Swift 3: func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {} ___AND___ func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {} – Naloiko Eugene Feb 09 '17 at 13:52
28

I've run into this same problem. Just send a viewWillAppear message to your view controller before you add it as a subview. (There is one BOOL parameter which tells the view controller if it's being animated to appear or not.)

[myViewController viewWillAppear:NO];

Look at RootViewController.m in the Metronome example.

(I actually found Apple's example projects great. There's a LOT more than HelloWorld ;)

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
lajos
  • 25,525
  • 19
  • 65
  • 75
  • 3
    Actually, you should call viewWillAppear after you add it to the subview. Otherwise, IBOutlets/IBActions won't be wired up. – 4thSpace Jun 17 '09 at 15:37
  • 2
    Yes, afterwards. Created subview from XIB, viewWillAppear wasn't called. Call it by myself and everything works just fine. – JOM Feb 16 '10 at 07:03
  • Thank you! This was exactly it for me. I was manually adding a subview via `[scrollView addSubview:controller.view];`. I added the line `[controller viewWillAppear:NO];` afterwards and voila! Worked like a charm. – Rob S. May 09 '10 at 18:43
  • In all likelyhood, this is because your UIViewController is controlling a view which is a subview of a view controlled by another UIViewController. This is not the intended design pattern. For more explanation check out this post. http://stackoverflow.com/questions/5691226/am-i-abusing-uiviewcontroller-subclassing/5691708#comment-6507338 – averydev Apr 17 '11 at 23:28
  • 6
    Please beware!!! No longer true on iOS 5 !!! Calls viewWillAppear and viewDidAppear automatically. If you called it manually, it would be called twice. – Vilém Kurz Nov 10 '11 at 17:24
  • With nested view, I still have to call this manually even for iOS7. Then it works beautifully. – juminoz Aug 29 '13 at 01:02
  • How if child view controller is added from storyboard? – Mubin Mall Jan 07 '16 at 12:48
  • it have never been correct - sometimes you call `viewWillAppear:` and system calls the same method. `viewWillAppear:` in your own class always calls `[super viewWillAppear:animated];`. Calling it twice may have unpredictable result. And of course - why have you chosen an existing delegate method instead of your own? – Vyachaslav Gerchicov Apr 04 '17 at 15:21
18

I finally found a solution for this THAT WORKS!

UINavigationControllerDelegate

I think the gist of it is to set your nav control's delegate to the viewcontroller it is in, and implement UINavigationControllerDelegate and it's two methods. Brilliant! I'm so excited i finally found a solution!

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Chris
  • 39,719
  • 45
  • 189
  • 235
11

Thanks iOS 13.

ViewWillDisappear, ViewDidDisappear, ViewWillAppear and ViewDidAppear won't get called on a presenting view controller on iOS 13 which uses a new modal presentation that doesn't cover the whole screen.

Credits are going to Arek Holko. He really saved my day.

enter image description here

BilalReffas
  • 8,132
  • 4
  • 50
  • 71
9

I just had the same issue. In my application I have 2 navigation controllers and pushing the same view controller in each of them worked in one case and not in the other. I mean that when pushing the exact same view controller in the first UINavigationController, viewWillAppear was called but not when pushed in the second navigation controller.

Then I came across this post UINavigationController should call viewWillAppear/viewWillDisappear methods

And realized that my second navigation controller did redefine viewWillAppear. Screening the code showed that I was not calling

[super viewWillAppear:animated];

I added it and it worked !

The documentation says:

If you override this method, you must call super at some point in your implementation.

Antoine
  • 121
  • 1
  • 1
5

I've been using a navigation controller. When I want to either descend to another level of data or show my custom view I use the following:

[self.navigationController pushViewController:<view> animated:<BOOL>];

When I do this, I do get the viewWillAppear function to fire. I suppose this qualifies as "indirect" because I'm not calling the actual addSubView method myself. I don't know if this is 100% applicable to your application since I can't tell if you're using a navigation controller, but maybe it will provide a clue.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Josh Gagnon
  • 5,342
  • 3
  • 26
  • 36
4

Firstly, the tab bar should be at the root level, ie, added to the window, as stated in the Apple documentation. This is key for correct behavior.

Secondly, you can use UITabBarDelegate / UINavigationBarDelegate to forward the notifications on manually, but I found that to get the whole hierarchy of view calls to work correctly, all I had to do was manually call

[tabBarController viewWillAppear:NO];
[tabBarController viewDidAppear:NO];

and

[navBarController viewWillAppear:NO];
[navBarController viewDidAppear:NO];

.. just ONCE before setting up the view controllers on the respective controller (right after allocation). From then on, it correctly called these methods on its child view controllers.

My hierarchy is like this:

window
    UITabBarController (subclass of)
        UIViewController (subclass of) // <-- manually calls [navController viewWill/DidAppear
            UINavigationController (subclass of)
                UIViewController (subclass of) // <-- still receives viewWill/Did..etc all the way down from a tab switch at the top of the chain without needing to use ANY delegate methods

Just calling the mentioned methods on the tab/nav controller the first time ensured that ALL the events were forwarded correctly. It stopped me needing to call them manually from the UINavigationBarDelegate / UITabBarControllerDelegate methods.

Sidenote: Curiously, when it didn't work, the private method

- (void)transitionFromViewController:(UIViewController*)aFromViewController toViewController:(UIViewController*)aToViewController 

.. which you can see from the callstack on a working implementation, usually calls the viewWill/Did.. methods but didn't until I performed the above (even though it was called).

I think it is VERY important that the UITabBarController is at window level though and the documents seem to back this up.

Hope that was clear(ish), happy to answer further questions.

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Sam
  • 3,659
  • 3
  • 36
  • 49
3

Correct way to do this is using UIViewController containment api.

- (void)viewDidLoad {
     [super viewDidLoad];
     // Do any additional setup after loading the view.
     UIViewController *viewController = ...;
     [self addChildViewController:viewController];
     [self.view addSubview:viewController.view];
     [viewController didMoveToParentViewController:self];
}
Hari Kunwar
  • 1,661
  • 14
  • 10
  • This is absolutely the correct modern solution (iOS 9,8,7). Also, if you are changing the embedded view controller on the fly, you will need to call [viewController willMoveToParentViewController:nil]; [viewController.view removeFromSuperview]; [viewController removeFromParentViewController]; – Eli Burke Sep 22 '15 at 17:42
  • 1
    In this case `viewWillAppear:` may still not be called – Vyachaslav Gerchicov Apr 04 '17 at 15:29
3

Views are added "directly" by calling [view addSubview:subview]. Views are added "indirectly" by methods such as tab bars or nav bars that swap subviews.

Any time you call [view addSubview:subviewController.view], you should then call [subviewController viewWillAppear:NO] (or YES as your case may be).

I had this problem when I implemented my own custom root-view management system for a subscreen in a game. Manually adding the call to viewWillAppear cured my problem.

AndrewS
  • 8,196
  • 5
  • 39
  • 53
3

As no answer is accepted and people (like I did) land here I give my variation. Though I am not sure that was the original problem. When the navigation controller is added as a subview to a another view you must call the viewWillAppear/Dissappear etc. methods yourself like this:

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

    [subNavCntlr viewWillAppear:animated];
}

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

    [subNavCntlr viewWillDisappear:animated];
}

Just to make the example complete. This code appears in my ViewController where I created and added the the navigation controller into a view that I placed on the view.

- (void)viewDidLoad {

    // This is the root View Controller
    rootTable *rootTableController = [[rootTable alloc]
                 initWithStyle:UITableViewStyleGrouped];

    subNavCntlr = [[UINavigationController alloc]   
                  initWithRootViewController:rootTableController];

    [rootTableController release];

    subNavCntlr.view.frame = subNavContainer.bounds;

    [subNavContainer addSubview:subNavCntlr.view];

    [super viewDidLoad];
}

the .h looks like this

@interface navTestViewController : UIViewController <UINavigationControllerDelegate> {
    IBOutlet UIView *subNavContainer;
    UINavigationController *subNavCntlr;
}

@end

In the nib file I have the view and below this view I have a label a image and the container (another view) where i put the controller in. Here is how it looks. I had to scramble some things as this was work for a client.

alt text

hol
  • 8,255
  • 5
  • 33
  • 59
2

I use this code for push and pop view controllers:

push:

[self.navigationController pushViewController:detaiViewController animated:YES];
[detailNewsViewController viewWillAppear:YES];

pop:

[[self.navigationController popViewControllerAnimated:YES] viewWillAppear:YES];

.. and it works fine for me.

Leigh
  • 28,765
  • 10
  • 55
  • 103
Arash Zeinoddini
  • 801
  • 13
  • 19
2

A very common mistake is as follows. You have one view, UIView* a, and another one, UIView* b. You add b to a as a subview. If you try to call viewWillAppear in b, it will never be fired, because it is a subview of a

gdm
  • 7,647
  • 3
  • 41
  • 71
2

iOS 13 bit my app in the butt here. If you've noticed behavior change as of iOS 13 just set the following before you push it:

yourVC.modalPresentationStyle = UIModalPresentationFullScreen;

You may also need to set it in your .storyboard in the Attributes inspector (set Presentation to Full Screen).

This will make your app behave as it did in prior versions of iOS.

dollardime
  • 145
  • 11
1

I'm not 100% sure on this, but I think that adding a view to the view hierarchy directly means calling -addSubview: on the view controller's view (e.g., [viewController.view addSubview:anotherViewController.view]) instead of pushing a new view controller onto the navigation controller's stack.

Martin Gordon
  • 36,329
  • 7
  • 58
  • 54
1

I just had this problem myself and it took me 3 full hours (2 of which googling) to fix it.

What turned out to help was to simply delete the app from the device/simulator, clean and then run again.

Hope that helps

Finn Gaida
  • 4,000
  • 4
  • 20
  • 30
1

I think what they mean "directly" is by hooking things up just the same way as the xcode "Navigation Application" template does, which sets the UINavigationController as the sole subview of the application's UIWindow.

Using that template is the only way I've been able to get the Will/Did/Appear/Disappear methods called on the object ViewControllers upon push/pops of those controllers in the UINavigationController. None of the other solutions in the answers here worked for me, including implementing them in the RootController and passing them through to the (child) NavigationController. Those functions (will/did/appear/disappear) were only called in my RootController upon showing/hiding the top-level VCs, my "login" and navigationVCs, not the sub-VCs in the navigation controller, so I had no opportunity to "pass them through" to the Nav VC.

I ended up using the UINavigationController's delegate functionality to look for the particular transitions that required follow-up functionality in my app, and that works, but it requires a bit more work in order to get both the disappear and appear functionality "simulated".

Also it's a matter of principle to get it to work after banging my head against this problem for hours today. Any working code snippets using a custom RootController and a child navigation VC would be much appreciated.

Bogatyr
  • 19,255
  • 7
  • 59
  • 72
1

In case this helps anyone. I had a similar problem where my ViewWillAppear is not firing on a UITableViewController. After a lot of playing around, I realized that the problem was that the UINavigationController that is controlling my UITableView is not on the root view. Once I fix that, it is now working like a champ.

TryTryAgain
  • 7,632
  • 11
  • 46
  • 82
Andrew
  • 11
  • 1
1
[self.navigationController setDelegate:self];

Set the delegate to the root view controller.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Gaurav
  • 8,227
  • 4
  • 34
  • 55
1

In my case problem was with custom transition animation. When set modalPresentationStyle = .custom viewWillAppear not called

in custom transition animation class need call methods: beginAppearanceTransition and endAppearanceTransition

ober
  • 2,363
  • 1
  • 19
  • 17
1

For Swift. First create the protocol to call what you wanted to call in viewWillAppear

protocol MyViewWillAppearProtocol{func myViewWillAppear()}

Second, create the class

class ForceUpdateOnViewAppear: NSObject, UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool){
    if let updatedCntllr: MyViewWillAppearProtocol = viewController as? MyViewWillAppearProtocol{
        updatedCntllr.myViewWillAppear()
    }
}

}

Third, make the instance of ForceUpdateOnViewAppear to be the member of the appropriate class that have the access to the Navigation Controller and exists as long as Navigation controller exists. It may be for example the root view controller of the navigation controller or the class that creates or present it. Then assign the instance of ForceUpdateOnViewAppear to the Navigation Controller delegate property as early as possible.

Vadim Motorine
  • 2,973
  • 1
  • 11
  • 7
1

I think that adding a subview doesn't necessarily mean that the view will appear, so there is not an automatic call to the class's method that it will

0

In my case that was just a weird bug on the ios 12.1 emulator. Disappeared after launching on real device.

coldembrace
  • 549
  • 8
  • 19
0

I have created a class that solves this problem. Just set it as a delegate of your navigation controller, and implement simple one or two methods in your view controller - that will get called when the view is about to be shown or has been shown via NavigationController

Here's the GIST showing the code

GregJaskiewicz
  • 456
  • 3
  • 11
0

ViewWillAppear is an override method of UIViewController class so adding a subView will not call viewWillAppear, but when you present, push , pop, show , setFront Or popToRootViewController from a viewController then viewWillAppear for presented viewController will get called.

Abu Ul Hassan
  • 1,340
  • 11
  • 28
0

My issue was that viewWillAppear was not called when unwinding from a segue. The answer was to put a call to viewWillAppear(true) in the unwind segue in the View Controller that you segueing back to

@IBAction func unwind(for unwindSegue: UIStoryboardSegue, ViewController subsequentVC: Any) {

   viewWillAppear(true)
}
-2

I'm not sure this is the same problem that I solved.
In some occasions, method doesn't executed with normal way such as "[self methodOne]".

Try

- (void)viewWillAppear:(BOOL)animated
{
    [self performSelector:@selector(methodOne) 
           withObject:nil afterDelay:0];
}
Sean
  • 17
  • 4
-3

You should only have 1 UIViewController active at any time. Any subviews you want to manipulate should be exactly that - subVIEWS - i.e. UIView.

I use a simlple technique for managing my view hierarchy and have yet to run into a problem since I started doing things this way. There are 2 key points:

  • a single UIViewController should be used to manage "a screen's worth" of your app
  • use UINavigationController for changing views

What do I mean by "a screen's worth"? It's a bit vague on purpose, but generally it's a feature or section of your app. If you've got a few screens with the same background image but different overlays/popups etc., that should be 1 view controller and several child views. You should never find yourself working with 2 view controllers. Note you can still instantiate a UIView in one view controller and add it as a subview of another view controller if you want certain areas of the screen to be shown in multiple view controllers.

As for UINavigationController - this is your best friend! Turn off the navigation bar and specify NO for animated, and you have an excellent way of switching screens on demand. You can push and pop view controllers if they're in a hierarchy, or you can prepare an array of view controllers (including an array containing a single VC) and set it to be the view stack using setViewControllers. This gives you total freedom to change VC's, while gaining all the advantages of working within Apple's expected model and getting all events etc. fired properly.

Here's what I do every time when I start an app:

  • start from a window-based app
  • add a UINavigationController as the window's rootViewController
  • add whatever I want my first UIViewController to be as the rootViewController of the nav controller

(note starting from window-based is just a personal preference - I like to construct things myself so I know exactly how they are built. It should work fine with view-based template)

All events fire correctly and basically life is good. You can then spend all your time writing the important bits of your app and not messing about trying to manually hack view hierarchies into shape.

Nigel Flack
  • 108
  • 1
  • 4
  • There's nothing wrong with having multiple view controllers active; UIViewController has methods to allow a hierarchy to be constructed (e.g. [addChildViewController:]). – Richard Sep 20 '13 at 08:34
  • 1
    Yes it does now. In 2011 it didn't. The answer was accurate at the time, admittedly it isn't now. – Nigel Flack Sep 22 '13 at 16:10