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

在iOS开发中,当只有tabBarController且需从任意页面跳转时,遇到无法获取当前UINavigationController的问题。文章揭示了presentViewController方法下视图层级的变化,特别是UITransitionView的角色,它持有被present的控制器而非UIWindow。解决方案是利用UIViewController的presentedViewController属性,通过循环获取最顶层的presented控制器。最后,作者强调通过探究系统设计思路来解决问题的重要性。

背景故事

  • 工作中遇到一种应用场景。 在只能拿到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 在视图层级中是如何存在。
  • present后的controller
  • rootController push 出来的 controller
  • 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的实例。那么就可以去看看有没有类似的属性可以拿到。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值