Search code examples
iosuser-interfaceviewswiftuiz-index

Create a view over navigationView, SwiftUI


I'm creating a view embedded in a ZStack, something like this:

ZStack(alignment: .top) {
        
    content
        
        if self.show {
                                
                VStack {
                    
                    HStack {

This is a viewModifier so I call this in my main view with for example: .showView().

But what happened is that if I have a NavigationView, this view is only showing below the navigationView. (I have a navigationViewTitle that is over my view).

How can I solve this problem? I was thinking about some zIndex but it is not working. I thought also about some better placement of this .showView(), but nothing to do.


Solution

  • Here is a demo of possible approach (it can be added animations/transitions, but it is out of topic). Demo prepared & tested with Xcode 11.4 / iOS 13.4

    demo

    struct ShowViewModifier<Cover: View>: ViewModifier {
        let show: Bool
        let cover: () -> Cover
    
        func body(content: Content) -> some View {
            ZStack(alignment: .top) {
                content
                if self.show {
                    cover()
                }
            }
        }
    }
    
    struct DemoView: View {
        @State private var isPresented = false
        var body: some View {
            NavigationView {
                VStack {
                    NavigationLink("Link", destination: Button("Details")
                        { self.isPresented.toggle() })
                    Text("Some content")
                        .navigationBarTitle("Demo")
                    Button("Toggle") { self.isPresented.toggle() }
                }
            }
            .modifier(ShowViewModifier(show: isPresented) {
                Rectangle().fill(Color.red)
                    .frame(height: 200)
            })
        }
    }