如何在iOS的applicationWillEnterForeground中检测当前显示的视图?
如何判断iOS应用进入前台时当前显示的视图控制器
嘿,我来帮你搞定这个问题~你的思路方向是对的,但直接在applicationWillEnterForeground里用storyboardID判断可能行不通,因为这个方法里没法直接拿到当前正在显示的视图控制器实例。下面给你一套靠谱的实现方案:
第一步:写个工具方法获取当前最顶层的视图控制器
应用里的视图层级往往是嵌套的(比如导航控制器、标签栏控制器、模态弹出的VC),所以我们需要一个能遍历找到最上层可见VC的方法,直接写个UIApplication的扩展就行:
extension UIApplication { func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { // 处理导航控制器,取当前显示的VC if let navigationController = controller as? UINavigationController { return topViewController(controller: navigationController.visibleViewController) } // 处理标签栏控制器,取选中的VC if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return topViewController(controller: selected) } } // 处理模态弹出的VC,取最上层的弹出VC if let presented = controller?.presentedViewController { return topViewController(controller: presented) } // 最终返回最顶层的VC return controller } }
第二步:在进入前台的方法里判断当前VC
接下来就可以在applicationWillEnterForeground(或者iOS13+的sceneWillEnterForeground)里调用这个方法,然后判断当前VC:
func applicationWillEnterForeground(_ application: UIApplication) { // 获取当前最顶层的视图控制器 guard let currentVC = UIApplication.shared.topViewController() else { return } // 方式1:通过Storyboard ID判断(注意这里用restorationIdentifier,Storyboard里设置的ID会赋值给这个属性) if currentVC.restorationIdentifier == "myview" { // 执行你需要的操作 print("当前显示的是myview对应的页面") } // 方式2:直接判断VC类型(更推荐!比字符串ID更安全,重构时不容易出错) if currentVC is MyViewController { // 强转后可以直接调用VC里的方法 let myVC = currentVC as! MyViewController myVC.doCustomAction() } }
额外注意(iOS13+)
如果你的应用适配了iOS13及以上,使用了SceneDelegate,那需要把上面的判断逻辑放到SceneDelegate的sceneWillEnterForeground(_:)方法里,代码逻辑完全一样,只是方法所在的类不同。
内容的提问来源于stack exchange,提问作者Utku Dalmaz
相关产品推荐
相关产品推荐

