Brice Brice -4 years ago 123
iOS Question

Something like prepareForSegue but for when going back

In my iOS app, I'm using a UINavigationController with segues setup in Xcode. For one of the views, I want to hide the navigation bar, and for the others, I want it to show up. I am able to successfully hide the bar in the main view, then nicely animate it in when I segue to the next view, but when I go back (using the back button in the navigation bar), the bar just disappears, leaving a black rectangle, then switches back to the previous view. I would like to be able to catch this, with something like the opposite of prepareForSegue, and nicely animate the navigation bar out. Is there some way to do this?

Answer Source

There currently is no prepareForDesegue:sender: alternative to prepareForSegue:sender:. The recommended practice is to establish a reference, in the destination ViewController, back to the source ViewController. Then, when the destination ViewController is dismissed, it can notify the source ViewController that it is about to become the top ViewController again. Typically, the reference is established in prepareForSegue:sender:.

So, to make this concrete, let's suppose that you have ViewControllerA, and are about to segue to ViewControllerB. In ViewControllerB, you would define a property that references ViewControllerA. (This is often done using protocols, but to make it simple, just assume that ViewControllerB has @property ViewControllerA *delegate;.) Then, in prepareForSegue:sender:, you would do the following:

ViewControllerB * vcB = (ViewControllerB *)[segue destinationViewController];
vcB.delegate = self;

Later, in ViewControllerB, in whatever code is about to get you back to ViewControllerA, you would use self.delegate to reach back to ViewControllerA, and let it know it's about to be presented, and give it the opportunity to do whatever you need to with the UINavigationBar.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download