Modal presentation with NavigationView

Viewed 611

I need to present a view with ModalPresentation and it contains a NavigationView and ScrollView because the content will be a form with many fields.

My code is as follows and is working correctly in portrait mode but when I change to landscape mode the content disappears and nothing is displayed.

struct ContentView: View {
    @State var showingDetail = false

    var body: some View {
        Button(action: {
            self.showingDetail.toggle()
        }) {
            Text("Show Detail")
        }.sheet(isPresented: $showingDetail) {
            Detail()
        }
    }
}


struct Detail: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var body: some View {
        NavigationView {
            ScrollView {
                VStack {
                Text("Details view")
                Text("Details view")
                }

            }
            .navigationBarTitle("Booking", displayMode: .inline)

            .navigationBarItems(trailing:
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                    print("close")
                }) { Image(systemName: "xmark")  }).accentColor(.pink)

        }
    }
}

Any suggestions to work both: portrait and landscape.

  • NOTE: If I cancel the NavigationView, it works.

UPDATE View image: In landscape it shows but if sliding from the left, but I want it to be displayed without sliding.

Landscape

2 Answers

There's nothing wrong with your code. You just need to use the following .compact mode to support Landscape orientation:

NavigationView {
    ...
}.environment(\.horizontalSizeClass, .compact)

It works fine for me on Xcode Version 11.2 beta (11B41) w/ iPhone Xs Max running iOS 13.1.2.

enter image description here

VStack must be aligned -> VStack(alignment: HorizontalAlignment.center)

With that you must work correctly

struct Detail: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var body: some View {
        NavigationView {
            ScrollView {

                VStack(alignment: HorizontalAlignment.center) {
                     Text("Width: ")
                     Text("Height: ")

                 }

            }

            .navigationBarTitle("Booking", displayMode: .inline)

            .navigationBarItems(trailing:
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                    print("close")
                }) { Image(systemName: "xmark")  }).accentColor(.pink)



        } .environment(\.horizontalSizeClass, .compact)
    }
}

enter image description here

Related