核心在于 UIHostingController
https://developer.apple.com/documentation/swiftui/uihostingcontroller
示例代码
https://github.com/shankarmadeshvaran/SwiftUI_Tasks
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
// Get the managedObjectContext from the persistent container
let managedObjectContext = (UIApplication.shared.delegate as? AppDelegate)!.persistentContainer.viewContext
// Pass it to the ContentView through the managedObjectContext @Environment variable
let homeTasksView = HomeTasksView()
.environment(\.managedObjectContext, managedObjectContext)
window.rootViewController = UIHostingController(rootView: homeTasksView)
self.window = window
window.makeKeyAndVisible()
}
}