You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从AppDelegate实例化视图控制器:代码执行正常但界面未显示如何解决

问题原因

iOS 13及以上版本中,应用的UI生命周期管理逻辑已从AppDelegate转移到SceneDelegate,你直接在AppDelegate中创建并赋值window属性不会生效,此时UI渲染由当前活跃UIWindowScene对应的SceneDelegate的window属性负责,因此会出现代码逻辑执行但页面不显示的问题。

解决方案

方案1:适配SceneDelegate(推荐,支持iOS13+新特性)

  1. 先确认你的SceneDelegate.swift中已声明window属性:
var window: UIWindow?
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:18:02