In SwiftUI, when using NavigationStack with a path binding containing multiple instances of the same (or many with navigationPath()) model type (since model type are class type, this issue might occur on instances of class type too), any NavigationLink in a detail view that leads to a value already present anywhere in the navigation stack (which is in the path binding) will appear incorrectly highlighted upon the view's initial appearance. This bug seems manifests specifically when the links are contained within a List. The highlighting is inconsistent - only the earliest appended value in path has link in each section displays as pressed, while links to other value appear normal.
Below is a simple code to reproduce the bug.
import SwiftUI
import SwiftData
// Simple model
@available(iOS 17, *)
@Model
class Item {
var id = UUID()
var name: String
var relatedItems: [Item]
init(name: String = "", relatedItems: [Item] = []) {
self.name = name
self.relatedItems = relatedItems
}
}
// MARK: - Bug Reproducer
@available(iOS 17, *)
struct BugReproducerView: View {
@State private var path: [Item] = []
let items: [Item]
init() {
let item1 = Item(name: "Item 1", relatedItems: [])
let item2 = Item(name: "Item 2", relatedItems: [item1])
item1.relatedItems = [item2]
self.items = [item1, item2]
}
var body: some View {
NavigationStack(path: $path) {
List(items) { item in
NavigationLink(item.name, value: item)
}
.navigationTitle("Items")
.navigationDestination(for: Item.self) { item in
DetailView(item: item)
}
}
}
}
// MARK: - Detail View with Bug
@available(iOS 17, *)
struct DetailView: View {
let item: Item
var body: some View {
List {
Section("Info") {
Text("Selected: \(item.name)")
}
if !item.relatedItems.isEmpty {
Section("Related") {
ForEach(item.relatedItems) { related in
NavigationLink(related.name, value: related)
}
}
}
}
.navigationTitle(item.name)
}
}
#Preview {
if #available(iOS 17, *) {
BugReproducerView()
} else {
}
}