Change the root view of UIHostingController in SwiftUI

前端 未结 5 929
情歌与酒
情歌与酒 2020-12-03 07:19

For a new SwiftUI iOS app, I do the following in the SceneDelegate

if let windowScene = scene as? UIWindowScene {
    let window =          


        
5条回答
  •  我在风中等你
    2020-12-03 07:55

    You can make a Router class

    import Foundation
    import UIKit
    import SwiftUI
    
    class Router {
        
        class var window: UIWindow? {
            if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                if let sceneDelegate = scene.delegate as? SceneDelegate {
                    let window = UIWindow(windowScene: scene)
                    sceneDelegate.window = window
                    window.makeKeyAndVisible()
                    return window
                }
            }
            return nil
        }
        
        static func showMain() {
            window?.rootViewController = UIHostingController(rootView: ContentView())
        }
        
    }
    

    Usage :

    Router.showMain()
    

    And with this you can decide which window you want as your root at any given time.

提交回复
热议问题