从任何 SwiftUI 视图访问当前的 UIWindowScene
和 UIWindow
。
使用 WindowSceneReader
读取当前的 UIWindowScene
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
WindowSceneReader { windowScene in
ContentView()
}
}
}
}
或者,如果只需要子视图上的 window scene,只需添加 windowScene()
。
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.windowScene()
}
}
}
在子视图上,UIWindowScene
将在 Environment
中可用
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
let rootView = ContentView()
.windowScene(windowScene)
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: rootView)
self.window = window
window.makeKeyAndVisible()
}
}
@Environment(\.windowScene) var windowScene
@Environment(\.windowScene) var windowScene
默认设置为第一个连接的 UIWindowScene
,如果没有连接的 UIWindowScene
,则为 nil
。
请参阅 LICENSE