0

In my app I have a View inside another, and I want to navigate to another view from the subview, with a NavigationStack. The problem is that the navigation takes place at the top view level.

I only want to replace the subview with another subview with navigation. In UIKit it works fine (with ContainerView), but I can't find the way to do it using SwiftUI.

I attach some simplified code of the app.


@available(iOS 16.0, *)
struct PruebaNavigationInside: View {
    var body: some View {
        NavigationStack {
            VStack {
                HeaderView()
                NotesView()
            }
        }
    }
}

@available(iOS 16.0, *)
struct HeaderView: View {
    var body: some View {
        VStack {
            Text("Header")
                .padding()
            Image(systemName: "globe")
        }
        .font(.largeTitle)
        .bold()
        .padding()
    }
}
    
@available(iOS 16.0, *)
struct NotesView: View {
    var body: some View {
        List {
            ForEach(1..<10, id:\.self) { i in
                
                NavigationLink("Not2 \(i)") {
                    NoteDetailView(note: "Note \(i)")
                }
            }
            
        }
    }
}
@available(iOS 16.0, *)
struct NoteDetailView: View {
    
    var note: String
    
    var body: some View {
        Text(note)
    }
}

@available(iOS 16.0, *)
struct PruebaNavigationInside_Previews: PreviewProvider {
    static var previews: some View {
        PruebaNavigationInside()
    }
}

I attach an image to clarify the question. I want that the header remains, and the only thing changing is the part of the list.

Header and List

Thanks in advance!

1 Answers1

0

So UIKit and SwiftUI reuse some navigation lingo but they behave very differently.

Views and UIViews are very different, UIViews are directly rendered objects on screen, which get drawed using the ‘draw’ function, while Views are only instructions for the SwiftUI renderer.

It’s the same reason you can put a NavigationView as a subview and it’ll still work.

So anyway, tl;dr: The approach here would be to forgo SwfitUI navigation, and instead write your own, displaying different views with a ‘push’ animation like NavigationViews do based on some variable.