Reference to source view controller and destinatio

2019-09-08 01:36发布

问题:

I have a series of UIViewControllers throughout my application. Most of them have the navigation bar but some of them hide it.

The problem is that sometimes as you transition between a view with or without navbars to another view with or without navbars there is a black box that replaces the navbar during the transition. This problem was discussed here: Hiding a UINavigationController's UIToolbar during viewWillDisappear:

This solution is fine and it does get rid of the black box, but I really don't want what was described as a "Cheshire Cat" disappearance. I've tried myriad solutions using prepareForSegue, ViewWillAppear, viewWillDisappear, etc. The best I can do is change the scenario in which the black bar shows up.

By this I mean, there are four combinations of view transitions between the two navigation bar states (hidden vs. not-hidden):

  • Hidden - Hidden
  • Hidden - Not Hidden
  • Not Hidden - Hidden
  • Not Hidden - Not Hidden

No matter what solution I've tried, at least one of those combinations results in my black box rearing its ugly head. The problem I have is that I've been unable to find anywhere that I can get a reference to the source view controller and the destination view controller when popping a view off of the navigation controller's view stack.

If I could get both references in the same event, I could simply determine what the combination is and handle the behavior appropriately like I would in prepare for segue.

Now, I know that "it's not possible" is a reasonable (and even a probable) answer, but I won't accept that as a solution alone. If it is indeed not possible, I'd like thoughts on a reasonable alternative. For example, I could handle all view controller popping manually (including the default back button) and thus could get the "upcoming controller" from the navigation controller's stack.

I would just prefer a solution using built in APIs or at least a solution where my controllers didn't have to be aware of their own navigation bar states.

Thanks a lot, Patrick

回答1:

I think UINavigationControllerDelegate is what you're after. It declares two methods:

  • -navigationController:willShowViewController:animated:

  • -navigationController:didShowViewController:animated:

All you need to do is set yourself as the delegate of the parent navigation controller and implement these methods to be notified of incoming view controllers.

Having said that, I've never needed to resort to this for hiding and showing navigation bars. Strictly speaking, view controllers where the navigation bar will always be visible never touch the navigation bar's visibility. When I'm moving into a view controller where it needs to hide, that view controller is responsible for hiding and setting it back to its prior state before disappearing. Following these standards has proven reliable for me.