I've been hitting a weird SwiftUI bug with navigation and state loss and I've managed to reproduce in a very tiny sample project. I've submitted a Feedback FB21681608 but thought it was worth posting here incase any SwiftUI experts can see something obviously wrong.
The bug
With deeper levels of navigation hierarchy SwiftUI will dismiss views when backgrounding the app.
Any work around would be appreciated. This happens in a real app where we have to navigate to a settings screen modally and then a complex flow with other sheets.
Sample code
Happens in the simulator and on device.
import SwiftUI
struct ContentView: View {
@State private var isPresented = false
var body: some View {
Button("Show first sheet") {
isPresented = true
}
.sheet(isPresented: $isPresented) {
SheetView(count: 1)
}
}
}
struct SheetView: View {
private enum Path: Hashable {
case somePath
}
@State private var isPresented = false
var count: Int
var body: some View {
NavigationStack {
VStack {
Text("Sheet \(count)")
.font(.largeTitle)
// To recreate bug show more than 4 sheets and then switch to the app switcher (CTRL-CMD-Shift-H).
// All sheets after number 3 dismiss.
Button("Show sheet: \(count + 1)") {
isPresented = true
}
}
.sheet(isPresented: $isPresented) {
SheetView(count: count + 1)
}
// Comment out the `navigationDestination` below and the sheets don't dismiss when app goes to the background.
// Or move this modifier above the .sheet modifier and the sheets don't dismiss.
.navigationDestination(for: Path.self) { _ in
fatalError()
}
}
}
}