首页 > 解决方案 > SwiftUI:macOS 应用程序的 fullScreenCover 等效项?

问题描述

我正在编写一个跨平台的 SwiftUI 应用程序,如果用户希望“锁定”应用程序,它需要提供密码提示。锁定屏幕应覆盖应用程序中的所有视图,直到用户成功进行身份验证。在 iOS 上,我可以使用以下fullScreenCover方法执行此操作:

.fullScreenCover(isPresented: $isLocked, content: {
        ApplicationLockView(viewModel: ApplicationLockViewModel())
    })

这很好用。但是,此方法在 macOS 上不可用。是否有在 macOS 上实现此功能的等效方法?

标签: iosswiftmacosswiftui

解决方案


fullScreenCover(isPresented:onDismiss:content:)确实支持Mac Catalyst 14.0+。

为目标启用 mac 支持:

在此处输入图像描述

用于在 mac 上测试的源代码:

struct ContentView: View {
    @State private var isPresented = false
    var body: some View {
        Button("Present") {
            isPresented.toggle()
        }
        .fullScreenCover(isPresented: $isPresented) {
            ModalView()
        }
    }
}
struct ModalView: View {
    @Environment(\.presentationMode) var presentationMode
    var body: some View {
        Button("Dismiss") {
            presentationMode.wrappedValue.dismiss()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.blue)
        .edgesIgnoringSafeArea(.all)
    }
}

使用移动边缘过渡:

struct ContentView: View {
    @State private var isPresented = false
    var body: some View {
        ZStack {
            Button("Present", action: {
                withAnimation(.linear) {
                    self.isPresented.toggle()
                }
            })
            
            if isPresented {
                ModalView(isPresented: self.$isPresented).transition(.move(edge: .bottom))
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

struct ModalView: View {
    @Binding var isPresented: Bool
    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color.blue)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            VStack {
                Button("Dismiss",action: {
                    withAnimation(.linear) {
                        self.isPresented.toggle()
                    }
                })
            }
        }
    }
}

推荐阅读