SwiftUI Navigation Link Selection's Highlight Not Working

78 Views Asked by At

In iOS, when you tap a row in a list to navigation to a page, the row gets highlighted to indicate which row is selected. This is not working for me when I have a NavigationStack(path:root:) that uses NavigationLink(_ titleKey:value:) and navigationDestination(for:destination).

Highlight doesn't work in the code below for me neither in Simulator nor device:

import SwiftUI

struct ExperimentView: View {
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            List {
                NavigationLink("Page", value: 0)
                NavigationLink("Page", value: 1)
                NavigationLink("Page", value: 2)
            }
            .navigationTitle("List")
            .navigationDestination(for: Int.self) { int in
                Text(int.description)
            }
        }
    }
}

But it works just fine when I use NavigationStack(root:) that uses NavigationLink(_ titleKey:destination).

1

There are 1 best solutions below

0
lorem ipsum On

This is one of the core differences between NavigationStack and NavigationSplitView.

The selection only works with NavigationSplitView I assume it is because the List does not stay on the screen with NavigationStack

struct ExperimentView: View {
    @State private var selection: Int?
    var body: some View {
        NavigationSplitView {
            List(selection: $selection) {
                NavigationLink("Page", value: 0)
                NavigationLink("Page", value: 1)
                NavigationLink("Page", value: 2)
            }
        } detail: {
            if let selection {
                Text(selection.description)

            } else {
                Text("Please select page.")
            }
        }
    }
}

https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types#Update-selection-based-navigation