20

I am having trouble with navigation in SwiftUI. I have a button on a navigation bar, if clicked it pushes a new navigation view with list of items. When one of those items is tapped, it pushes a detail view.

But I am ending up with something like this. enter image description here

Below is the code

struct FirstView: View {

   var body: some View {
       NavigationView {
           List {
            ...
           }
           .navigationBarTitle(Text("First View"))
           .navigationBarItems(trailing: MyButton())
       }
    }
}

struct MyButton: View {
    var body: some View {
        NavigationLink("SecondView", destination: SecondView())
    }
}

struct SecondView: View {
   var body: some View {
       NavigationView {
           Text("My View")
       }
   }
}

2 Answers 2

46

Remove the NavigationView from SecondView.

The NavigationLink puts the second view inside the first views navigations view, so you do not need to put it inside a second one.

You can still update the title of the view from SecondView like so:

struct SecondView: View {
   var body: some View {
       Text("My View")
       .navigationBarTitle("Second View")
   }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Quinn is right. but if You don't want a big area above:

enter image description here

enter image description here

add:

struct SecondView: View {
   var body: some View {
       Text("My View")
        .navigationBarTitle("Second View", displayMode: .inline)
   }
}

1 Comment

This has been deprecated in favor of developer.apple.com/documentation/swiftui/view/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.