SwiftUI:导航栏和选项卡栏上的全屏视图

6 fullscreen swift swiftui

我正在尝试在 SwiftUI 中的应用程序上添加全屏视图。这样做的目的是要有一个淡入的“阴影”,使屏幕变暗并将焦点集中到自定义弹出窗口,从而禁用背景中的内容。请参阅下面的视觉示例:

我有什么我想要的是

我试图添加此阴影的视图嵌入在复杂的 NavigationView 堆栈中(几层深,通过 a 访问NavigationLink),并且还有一个可见的 TabBar。到目前为止,我已经尝试将NavigationViewa 嵌入ZStack并在顶部添加 aRectangle()但无济于事,NavigationBar 和 TabBar 仍然位于此视图的顶部。我也尝试过使用修饰符,.zIndex()但这似乎没有任何作用。

任何帮助深表感谢,

谢谢

use*_*ser 6

您不需要在 zIndex 上工作,因为您覆盖了整个屏幕!即使您不需要禁用当前视图来使用 PopUp,因为 PopUp 已经位于顶层。当你没有覆盖屏幕时,zIndex 会很有帮助,这里有一个方法:

struct ContentView: View {
    
    @State private var isPresented: Bool = Bool()
    
    var body: some View {
        
        NavigationView {
            
            VStack {
                
                Button("Show Custom PopUp View") { isPresented.toggle() }

            }
            .navigationTitle("Navigation Title")
            
        }
        .customPopupView(isPresented: $isPresented, popupView: { popupView })
        
    }
    
    var popupView: some View {
        
        RoundedRectangle(cornerRadius: 20.0)
            .fill(Color.white)
            .frame(width: 300.0, height: 200.0)
            .overlay(
                
                Image(systemName: "xmark").resizable().frame(width: 10.0, height: 10.0)
                    .foregroundColor(Color.black)
                    .padding(5.0)
                    .background(Color.red)
                    .clipShape(Circle())
                    .padding()
                    .onTapGesture { isPresented.toggle() }
                
                , alignment: .topLeading)
            
            .overlay(Text("Custom PopUp View!"))
            .transition(AnyTransition.scale)
            .shadow(radius: 10.0)
        
    }
}


struct CustomPopupView<Content, PopupView>: View where Content: View, PopupView: View {
    
    @Binding var isPresented: Bool
    @ViewBuilder let content: () -> Content
    @ViewBuilder let popupView: () -> PopupView
    let backgroundColor: Color
    let animation: Animation?
    
    var body: some View {
        
        content()
            .animation(nil, value: isPresented)
            .overlay(isPresented ? backgroundColor.ignoresSafeArea() : nil)
            .overlay(isPresented ? popupView() : nil)
            .animation(animation, value: isPresented)
        
    }
}

extension View {
    func customPopupView<PopupView>(isPresented: Binding<Bool>, popupView: @escaping () -> PopupView, backgroundColor: Color = .black.opacity(0.7), animation: Animation? = .default) -> some View where PopupView: View {
        return CustomPopupView(isPresented: isPresented, content: { self }, popupView: popupView, backgroundColor: backgroundColor, animation: animation)
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 应该提到的是,这仅在放置在根视图上时才有效。如果将其放置在 NavigationView 或 TabView 的视图层次结构中较深的位置,则某些 UI 元素(例如 navigationTitle、toolbarItems 或 tabItems)将不会被覆盖。 (9认同)
  • 是的。基本上这个答案是行不通的。 (3认同)