iOS开发:如何在LaunchScreen启动页顶部显示Alert弹窗?
问题根源
- 系统展示的
LaunchScreen.storyboard启动页是由SpringBoard直接控制的独立窗口,优先级远高于你的App内部的所有窗口,你在代码里手动实例化的launchScreenCtrler根本不是当前正在屏幕上显示的系统启动页实例,自然没法把弹窗加在真实启动页上面。 - 你在
willFinishLaunchingWithOptions阶段App的主窗口都还没初始化完成,就算你加了自定义视图也没有地方可以挂载显示,要等系统启动页自动消失之后你的App界面才会接管屏幕,这就是为什么弹窗要等启动页消失才出现的原因。
解决方案
苹果本身不允许开发者干预系统启动页的生命周期,不要尝试修改系统启动页的显示逻辑。你可以做一个和启动页1:1完全一致的假启动页容器,在系统启动页消失的瞬间把这个假启动页盖在App最上层,再在这个假启动页上展示你需要的弹窗,等用户处理完弹窗逻辑再把假启动页移除,用户完全感知不到切换。
实现代码示例
可以直接复用你现有LaunchScreen.storyboard的内容,不需要额外开发UI:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // 先初始化主窗口 window = UIWindow(frame: UIScreen.main.bounds) guard let window = window else { return true } if !conditionMet { // 加载和系统启动页完全一致的假启动页 let storyboard = UIStoryboard(name: "Launch Screen", bundle: nil) guard let fakeLaunchVC = storyboard.instantiateViewController(withIdentifier: "LAUNCH_SCREEN") as? UIViewController else { return true } // 把假启动页设为根控制器先显示,此时系统启动页刚好消失,用户无感知 window.rootViewController = fakeLaunchVC window.makeKeyAndVisible() // 现在在假启动页上弹出的alert就会显示在启动页视觉层级的顶部 let alert = UIAlertController(title: "提示", message: "运行条件不满足", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { _ in // 用户处理完弹窗后替换为App真正的根控制器即可 let realRootVC = 你的App原有主控制器() window.rootViewController = realRootVC })) fakeLaunchVC.present(alert, animated: true) } else { // 条件满足直接走原有启动逻辑 window.rootViewController = 你的App原有主控制器() window.makeKeyAndVisible() } return true }
内容的提问来源于stack exchange,提问作者user16780334
相关产品推荐
相关产品推荐

