Swift4中如何在AppDelegate获取NavigationController的初始视图实例
Hey there! 刚好你猜的方向没错,确实可以借助window属性来实现这个需求,我给你一步步拆解具体的实现方法:
核心思路
你的NavigationController作为storyboard的初始控制器,会被系统设置为window的根控制器。所以我们可以先拿到这个导航控制器,再从它的视图控制器数组中取出第一个(也就是你要的HotSpotRISViewController实例),之后就能直接给它的url变量赋值啦。
具体代码实现
你可以在AppDelegate的合适方法里(比如application(_:didFinishLaunchingWithOptions:),或者处理外部URL跳转的方法中)添加以下代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 1. 获取window的根控制器,并强转为UINavigationController guard let navigationController = window?.rootViewController as? UINavigationController else { print("根控制器不是UINavigationController") return true } // 2. 从导航控制器的viewControllers数组中取出第一个,强转为目标VC guard let hotspotVC = navigationController.viewControllers.first as? HotSpotRISViewController else { print("导航控制器的初始视图不是HotSpotRISViewController") return true } // 3. 这里就可以传递你的url变量了 hotspotVC.url = yourTargetURL // 替换成你实际的URL变量 return true }
注意事项
- 确保你的storyboard中,初始控制器确实是UINavigationController,并且这个导航控制器的根视图控制器就是
HotSpotRISViewController,不然强转的时候会失败(代码里的guard语句会帮你捕捉这种情况并打印提示)。 - 如果你的项目是iOS 13及以上版本,
window的管理可能迁移到了SceneDelegate中,那你需要在SceneDelegate的scene(_:willConnectTo:options:)方法里做类似的操作,但你用的是Swift 4,大概率还是基于AppDelegate的传统架构,上面的代码应该完全适用。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

