WindowKit

在 SwiftUI 中处理 UIWindow & UIWindowScene,并在它们自己的窗口中呈现 SwiftUI 视图。

用法

windowCover(isPresented:content:)

Static Badge

从任何 SwiftUI 视图中,在其自身的 UIWindow 内呈现一个模态视图。

用法类似于 fullscreenCover(isPresented:content:)

.windowCover(isPresented: $isPresented) {
    MyWindowCover()
}

您还可以配置窗口的呈现方式

.windowCover(isPresented: $isPresented) {
    MyWindowCover()
} configure { configuration in
    // Customize the window cover presentation
} 

环境

为了关闭窗口覆盖,请使用环境中的 dismissWindowCover

@Environment(\.dismissWindowCover) var dismiss

如果当前视图未在窗口覆盖中呈现,则 dismissWindowCover 操作将不执行任何操作。

windowOverlay(content:)

Static Badge

从任何 SwiftUI 视图中,在其自身的 UIWindow 内呈现一个模态视图。

用法类似于 overlay(content:)

.windowOverlay {
    MyWindowOverlay()
}

您还可以配置窗口的呈现方式

.windowOverlay {
    MyWindowOverlay()
} configure { configuration in
    // Customize the window overlay presentation
} 

WindowReader

Static Badge

使用 WindowReader 读取当前的 UIWindowNSWindow

@main
struct MyView: View {
    var body: some Scene {
        WindowReader { window in
            ...
        }
    }
}

在子视图中,UIWindowNSWindow 将在 Environment 中可用

环境

@Environment(\.window) var window

WindowSceneReader

Static Badge

SwiftUI 生命周期

使用 WindowSceneReader 读取当前的 UIWindowScene

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            WindowSceneReader { windowScene in
                ContentView()
            }
        }
    }
}

或者,如果您只需要子视图中的窗口场景,只需添加 windowScene()

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .windowScene()
        }
    }
}

在子视图中,UIWindowScene 将在 Environment 中可用

UIKit 生命周期

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