Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display missing back button in Master-Detail1-Detail2 view in SwiftUI in landscape?

I'm using a NavigationView and NavigationLinks to move from a MasterView to a Detail1View and then further to a Detail2View.

On an iPhone in portrait mode, the back button is displayed for all detail views and allows to move back from Detail2View to Detail1View, and then further to MasterView.

But on an iPhone in landscape mode or on an iPad, when moving from Detail1View to Detail2View, there is no back button. And it is thus impossible to go back to Detail1View.

Adding a 2nd NavigationView allows to have a back button, but it's not really a desirable workaround, as the 2nd UINavigationViewController is shown below the 1st one.

struct MyMasterView: View {
    private let names = ["Homer", "Marge", "Bart", "Lisa"]

    var body: some View {
        List() {
            Section(header: Text("The Simpsons")) {
                ForEach(names, id: \.self) { name in
                    NavigationLink(destination: MyDetail1View(name: name)) {
                        Text(name)
                    }
                }
            }
        }
        .navigationBarTitle(Text("My App"))
    }
}

struct MyDetail1View: View {
    var name: String

    var body: some View {
        //NavigationView {
            List {
                NavigationLink(destination: MyDetail2View(name: name)) {
                    Text("Hello \(name)")
                }
            }
            .navigationBarTitle(Text("Details 1"))
        //}
    }
}

struct MyDetail2View: View {
    var name: String

    var body: some View {
        HStack {
            Text("\(name), I'm sorry but in Landscape there is no back button...")
        }
        .navigationBarTitle(Text("Details 2"))
    }
}

struct ContentView : View {
    var body: some View {
        NavigationView {
            MyMasterView()
            Text("In Landscape, swipe to start...")
        }
    }
}
like image 309
caram Avatar asked Aug 12 '19 16:08

caram


People also ask

How do I hide the back button in SwiftUI?

The . navigationBarBackButtonHidden(true) will hide the back button.

How do I change the navigation bar in SwiftUI?

To customize a navigation bar title view in SwiftUI, we simply set ToolbarItem of placement type . principal to a new . toolbar modifier.


1 Answers

The answer turns out to be as simple as using isDetailLink()!

NavigationLink(destination: MyDetail2View(name: name)) {
   Text("Hello \(name)")
}.isDetailLink(false)

Credits to https://stackoverflow.com/a/57400873/2893408

like image 158
caram Avatar answered Nov 14 '22 22:11

caram