SwiftUI Navigation. View pops immediately after being pushed. How to fix?
I found a strange bug. In one moment view started popping immediately after being pushed. I had been commenting the code piece by piece until reduced it to a minimal reproducible example.
Here is the code:
struct Destination : View {
private let some: NSArray
init(some: NSArray) {
self.some = some
}
var body: some View {
Text("e")
}
}
struct RecordingsView : View {
var body: some View {
GeometryReader { geom in
// Fill safe area with colors
VStack {
Spacer().frame(maxWidth: .infinity, maxHeight: geom.safeAreaInsets.top).background(Color.red)
Spacer().frame(maxWidth: .infinity).background(Color.white)
}.edgesIgnoringSafeArea(.bottom).edgesIgnoringSafeArea(.top)
// Main content
VStack(spacing: 0) {
NavigationLink(
destination: Destination(some: NSArray(array: [34, 53, 45, 34566])).navigationBarHidden(true)
) {
Text("WhitePlusButton")
}.padding(.trailing, 18)
LazyVStack(spacing: 0) {
ForEach(0..<1) { index in
NavigationLink(
destination: Destination(some: NSArray(array: [34, 53, 45])).navigationBarHidden(true)
) {
Text("aaaaa")
}
}
}
}
}
}
}
@main
struct VocalTrainerApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
RecordingsView().navigationBarHidden(true)
}
}
}
}
However if I replace NSArray with Int or comment Spacer().frame(maxWidth: .infinity, maxHeight: geom.safeAreaInsets.top).background(Colors.tone2)
line, the bug is not reproduced.
You might be running into the bug where views pop immediately if there's exactly two navigation links. Try inserting a NavigationLink with EmptyViews as shown as a temporary bandaid.
NavigationLink(destination: EmptyView()) {
EmptyView()
}
You can find more info here: https://forums.swift.org/t/14-5-beta3-navigationlink-unexpected-pop/45279