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

如何用SwiftUI View替代UIViewController作为UIWindow的根视图控制器

问题解决方法

报错原因

rootViewController 仅接受 UIViewController 类型的实例,而你自定义的 WelcomeView 是 SwiftUI 体系下的 View 结构体,二者类型不兼容,无法直接赋值。

解决步骤

  1. 首先在 AppController 代码文件的头部引入 SwiftUI 依赖:
import SwiftUI
  1. 把 SwiftUI 视图用 UIHostingController 包装后再赋值给 rootViewController,UIHostingController 是 UIKit 提供的、专门用来承载 SwiftUI 视图的控制器类,本身继承自 UIViewController,完全符合类型要求。

修改你标记的代码块如下:

@objc private func handleAppState() {
  if let user = Auth.auth().currentUser {
    let channelsViewController = ChannelsViewController(currentUser: user)
    rootViewController = NavigationController(channelsViewController)
  } else {
    // 用UIHostingController包裹SwiftUI的WelcomeView
    rootViewController = UIHostingController(rootView: WelcomeView())
  }
}

可选扩展

如果需要和原有项目的导航逻辑保持一致,给 WelcomeView 套上你项目自定义的 NavigationController,可以写成:

rootViewController = NavigationController(UIHostingController(rootView: WelcomeView()))

内容的提问来源于stack exchange,提问作者Warren

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:09:03