今天由于项目需要,需要获得当前屏幕上显示ViewController,所以上网找了一下,找到下面这个方法,但使用的时候,发现并没有什么卵用。原因看下面。

接下来说一下我自己实践的方法。
APP的架构通常是 UITabBarViewController -> UINavigationController -> UIViewController.

所以我一开始的测试流程是:
UITabBarViewController --(push)-> WXPushViewController --(present)-> WXPresentViewController --(push)-> WXThreeViewController。
showVC 按钮是打印当前的类名。
第一步:获取默认的UIWindow,获取window的rootViewController

继续判断:如果window.rootViewController 是UITabBarViewController的话,就获取UITabBarViewController当前选中的ViewController.

继续判断:如果 result 是 UINavigationController 的话,就获取 UINavigationController 当前可见的ViewController(visibleViewController)

这里可以说一下 visibleViewController 和 topViewController的区别。
topViewController代表当前navigation栈中最上层的VC,
而visibleViewController代表当前可见的VC,它可能是topViewController,也可能是当前topViewController present出来的VC。
到这里,基本已经完成,但是在项目中运用的时候,却发现自己忽略了一种情况。
那就是 UINavigationViewController --> UIViewController --(present)-> UITabBarViewController这种情况,因为我在登录完成的时候 present一个新的UITabBarViewController出来。如果我们用上面的方法去获取当前显示ViewController,那么获取到的也永远只是UITabBarViewController。原因就出在visibleViewController身上。
为了解决这个问题,我们应该在获取window的rootViewController的时候,就循环获取最新的 被present 出来的ViewController,那么如何获取被present的ViewController呢?UIViewController提供了这么一个属性 presentedViewController 来让你获得被present出来的ViewController,如何循环遍历呢,直接加个while就可以了,具体看下面代码

到这里,全部结束。起码在我的项目中目前还没出现任何问题,如果有问题,可以留言。全部代码看下面:

总结:
visibleViewController 和 topViewController的区别?
topViewController代表当前navigation栈中最上层的VC,visibleViewController代表当前可见的VC,它可能是topViewController,也可能是当前topViewController present出来的VC。
presentedViewController 和 presentingViewController 的区别?
presentedViewController:The view controller that is presented by this view controlller(read-only),被本视图控制器present出来的的视图控制器
presentingViewController:The view controller that presented this view controller. (read-only),present出来本视图控制器的视图控制器
例如:
如A-->弹出B, 则A.presentedViewController = B
B.presentingViewController = A
如果你有兴趣可以上Github看看我的流程
网友评论