swiftuiswiftui-zstack

Show fullscreen popup in SwiftUI


I'm having problems showing fullscreen popups in SwiftUI. My app structure is a MainView with a TabView with 2 tabs.

This is a sample of my app structure:

struct UIMainView: View {
    
    var body: some View {
        
        ZStack {
            
            VStack(spacing: 0) {
                
                TabView() {
                  Tab1()
                  Tab2()
                }

                CustomTabBar()
                    .frame(height: 30)
            }
            .padding(.bottom, 32)
            .ignoresSafeArea(.keyboard, edges: .bottom)
        }
        .ignoresSafeArea()
    }
}

This is a sample of a view shown navigaing from any of the 2 tabs:

struct SampleView: View {
    
    var body: some View {
        
        NavigationView {
            
            ZStack {
        
                VStack {
                   // View components
                }

                if hasToShowPopup {
                    
                    FullscreenPopup()
                        .ignoresSafeArea()
                }
            }
         }  
    }
}

As you can see, this view contains the code to show a fullscreen popup. Its code is more or less this:

struct FullscreenPopup: View {
    
    var body: some View {
        
        ZStack {
            Spacer()
                    
            VStack {
              // Popup components
             }
                .padding()
                .frame(width: UIScreen.main.bounds.size.width - 66)
                .cornerRadius(8)

            Spacer()
        }
        .frame(width: UIScreen.main.bounds.size.width, 
               height: UIScreen.main.bounds.size.height)
        .background(Color.black.opacity(0.6))
    }
    
}

Well, although Fullscreen popup frame is set as the whole screen and it (and the rest of views) are inside some ZStack, the popup only occupies the place of the tab1 and tab2 views, it doesn't cover the CustomTabBar (so it still can be used, what is not my intention). So, how could I make my customtabbar covers the whole screen, including the CustomTabBar?


Solution

  • You can use .fullScreenCover

    struct SampleView: View {
        @State private var hasToShowPopup: Bool = false
        var body: some View {
            
            NavigationView {
                
                ZStack {
                    VStack {
                        Button("show cover") {
                            hasToShowPopup.toggle()
                        }
                    }
                    .fullScreenCover(isPresented: $hasToShowPopup) {
                        Text("Your View here")
                    }
                }
            }
        }
    }