Simon Bogutzky
Simon Bogutzky

Reputation: 50

Back button misalignment in NavigationView/NavigationStack within a sheet after orientation change

I observed this issue and added feedback to the Apple Feedback Assistant. However, here is the problem:

When switching from portrait to landscape format and back, the back button in the navigation stack or navigation view in a sheet moves inwards and no longer appears in its original position.

Maybe someone else has encountered the problem as well.

Example Code:

import SwiftUI

struct ContentView: View {
    @State private var sheetViewIsPresented: Bool = false
    
    var body: some View {
        Button("Present Sheet") {
            sheetViewIsPresented.toggle()
        }
        .sheet(isPresented: $sheetViewIsPresented) {
            SheetView()
        }
    }
}

struct SheetView: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: DetailView()) {
                Text("Navigate")
            }
        }
    }
}

struct DetailView: View {
    var body: some View {
        Text("Detail View")
    }
}

Upvotes: 0

Views: 28

Answers (1)

Benzy Neez
Benzy Neez

Reputation: 21665

NavigationView is deprecated. If you don't need to support iOS 15, use NavigationStack instead. But the issue is the same with NavigationStack.

A workaround is to use a GeometryReader to measure the size of the display area and then set this on the NavigationStack asynchronously:

struct SheetView: View {
    @State private var displaySize: CGSize?

    var body: some View {
        GeometryReader { proxy in
            NavigationStack {
                NavigationLink("Navigate") {
                    DetailView()
                }
            }
            .frame(maxWidth: displaySize?.width, maxHeight: displaySize?.height)
            .task(id: proxy.size) {
                displaySize = proxy.size
            }
        }
    }
}

Upvotes: 0

Related Questions