从AppDelegate实例化视图控制器:代码执行正常但界面未显示如何解决
问题原因
iOS 13及以上版本中,应用的UI生命周期管理逻辑已从AppDelegate转移到SceneDelegate,你直接在AppDelegate中创建并赋值window属性不会生效,此时UI渲染由当前活跃UIWindowScene对应的SceneDelegate的window属性负责,因此会出现代码逻辑执行但页面不显示的问题。
解决方案
方案1:适配SceneDelegate(推荐,支持iOS13+新特性)
- 先确认你的
SceneDelegate.swift中已声明window属性:
var window: UIWindow?
- 修改
AppDelegate中的Google登录回调代码,适配不同iOS版本:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { print("User Email: \(user.profile.email ?? "No Email")") let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let homeViewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.Storyboard.tabBarController) // iOS13及以上走Scene逻辑 if #available(iOS 13.0, *) { guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let sceneDelegate = windowScene.delegate as? SceneDelegate else { return } sceneDelegate.window?.rootViewController = homeViewController sceneDelegate.window?.makeKeyAndVisible() } else { // iOS12及以下保留原有逻辑 self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = homeViewController self.window?.makeKeyAndVisible() } }
方案2:禁用SceneDelegate(适合不需要多窗口功能的App)
- 打开
Info.plist,删除Application Scene Manifest条目 - 删除项目中的
SceneDelegate.swift文件 - 清空
AppDelegate.swift中所有和UISceneSession相关的代理方法 - 保留原有代码即可正常运行
注意事项
- 确保
Constants.Storyboard.tabBarController的取值和你在Main.storyboard中给对应控制器设置的Storyboard ID完全一致,大小写敏感 - 如果需要切换控制器时的过渡效果,可以在修改
rootViewController时添加UIView转场动画,避免跳转生硬
内容的提问来源于stack exchange,提问作者amirbt17
相关产品推荐
相关产品推荐

