您的位置:首页 > 移动开发 > IOS开发

IOS 使用presentViewController方法跳转的navigationController如何获取及视图层级关系

2018-03-22 11:21 603 查看

背景故事

工作中遇到一种应用场景。 在只能拿到tabBarController的情况下,需要在app内任何页面 跳转至新页面。

为什么会遇到问题

因为没办法获取到当前视图的UINavigationController,首先确定用的跳转方法是

(void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion NS_AVAILABLE_IOS(5_0);


遇到的问题:如果当前的页面是present过来的,就无法用tabBarController present至新页面,在不知道UIViewController有一个presentedViewController属性的前提。想通过[UIApplication sharedApplication].keyWindow.rootViewController 拿,发现present不会改变rootViewController。这就纳闷了,自然去想着弄清present过去的viewcontroller 在视图层级中是如何存在。





UITransitionView 的解释 :It’s difficult to say exactly what Apple will or won’t do however, adding a view to an undocumented view you retrieve from a superView message is not contentious. What you should not do (or be careful if you do do) is make assumptions about the view you are adding to. Specifically its class but even basic things like the fact that it even exists.

What are you trying to do? There may be a simpler way - like adding your view directly to the app’s UIWindow.

UITransitionView 是一个不公开的类,在保存controller 方面的作用应该和UINavigationController类似。 这也就是为什么present后 uiwindow.rootController 没有改变的原因。 因为它是被UITransitionView持有而不是uiwindow直接持有。

解决方法

其实uiviewcontroller是有presentedViewController这么一个属性,可以用一个while 循环直接拿到最后一层的present.

第2张图中,可以作为跳转的viewcontroller 有三个 MainTabBarController、NavigationController以及最后一个。这三个 controller 用present方法 其实效果是一致的。uiwindow.rootController,下所有的controller 使用present 方法 都等于 rootController使用, 获取presentedViewController都是获取rootController的presentedViewController。

总结经验

其实苹果设计ios这么一个系统的时候,整体思维都是类似。 uiviewcontroller竟然有present这个方法,在这个方法中,有传入的uiviewcontroller,那么就是能够获取到这个controller的实例。那么就可以去看看有没有类似的属性可以拿到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐