I have a NavigationView/List combination that allows programmatic selection. The basic concept is similar to the one described here: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-programmatic-navigation-in-swiftui
With so many things, this works fine on iOS, but on macOS there's an issue: the EmptyView from the NavigationView becomes visible as soon as an item is selected:
Does anybody know how to remove this unwanted EmptyView()?
Here's a demo project:
struct ContentView: View {
@ObservedObject private var state = State()
var body: some View {
NavigationView {
VStack {
List(state.items, id: \.self, selection: $state.selected) { item in
Text(item)
.buttonStyle(.borderless)
}
// navigation to the detail view if an item is selected
if let selected = state.selected {
NavigationLink(
destination: Text(selected),
isActive: state.hasSelectionBinding
) {
EmptyView()
}
}
}
}
}
}
class State: ObservableObject {
@Published var items: [String] = ["Item 1", "Item 2", "Item 3"]
@Published var selected: String?
var hasSelectionBinding: Binding<Bool> {
Binding(
get: { self.selected != nil },
set: {
if $0 == false {
self.selected = nil
}
}
)
}
}
EDIT 1: I've tried putting the NavigationLink into a background modifier on the stack, but now the "Empty View" appears next to "Item 3":
var body: some View {
NavigationView {
VStack {
List(state.items, id: \.self, selection: $state.selected) { item in
Text(item)
.buttonStyle(.borderless)
}
}
.background(Group {
// navigation to the detail view if an item is selected
if let selected = state.selected {
NavigationLink(
destination: Text(selected),
isActive: state.hasSelectionBinding
) {
EmptyView()
}
}
})
}
}

.backgroundinit(destinationName:isActive:label:)initializer shows the ghost image.NavigationLink(_:tag:selection:destination:)does not.