How to get the controller is currently being displayed by the code

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/WangErice/article/details/51584410

If we individually packaged with a separate class for a function, we hope that this class as independent as possible, thereby reducing dependence on the outside. For example, we want to get a separate package Address Book class, there must be a controller may present out of a ABPeoplePickerNavigationController, of course, we can pass a current through an external controller, but I felt quite awkward, so how can you get within a class the current controller is displayed it?

Although we can not get the controller currently being displayed directly, but each application has only one main window, we can get this UIWindow object, and then traverse to the current controller by a certain method. The keyWindow only a rootViewController, the controller either UITabBarController or a subclass, either UINavigationController or a subclass, either UIViewController or a subclass, Let us call it A, the controller then there are the push by them , present it, and then you can recursively, I was not very witty (~! ~)?

Here let us discuss classification:

a) If A is UITabbarController or a subclass, then we can easily pass easily find the next level controller selectedViewController properties;

b) If A is UINavigationController or a subclass, we can acquire the controller the controller a final push out of visibleViewController properties;

c) If A is UIViewController or a subclass, then the controller want to show up a controller, only to show a new way controller present, so we can

presentedViewController not be acquired at a null controller, if the controller is already in the blank is shown;

The top three cases has covered all types of controllers, so we can find the controller is currently being displayed by recursively.

The main codes are as follows:


It looks like to achieve, but requires careful classification. Guess shortcomings Where will?

For example, I chose to use animation push a new page, and then call this method, the acquisition is before the animation controllers.



Guess you like

Origin blog.csdn.net/WangErice/article/details/51584410