多项选择的 SwiftUI NavigationLink 问题

SwiftUI NavigationLink issue with multi selections

我对 SwiftUI 导航有疑问。为了说明这个问题,我做了一个汽车列表的简单示例,如果用户点击它,它会显示汽车的详细信息:

struct ContentView: View {
    var cars = [Car(name: "A"), Car(name: "B"), Car(name: "C"), Car(name: "D")]
    
    var body: some View {
        NavigationView {
            LazyVStack(spacing: 10) {
               ForEach(cars, id: \.self) { car in
                   NavigationLink(destination: {
                       CarDetailsView(viewModel: CarDetailsViewModel(car: car))
                   },
                   label: {
                       CarRowView(car: car)
                   })
               }
           }
        }
    }
}

struct CarDetailsView: View {
    @StateObject var viewModel: CarDetailsViewModel
    @Environment(\.presentationMode) private var presentationMode
    
    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
    }
}

class CarDetailsViewModel: ObservableObject {
    @Published var car: Car
    
    init(car: Car) {
        self.car = car
    }
}

struct Car: Hashable {
    var name: String
}

struct CarRowView: View {
    var car: Car
    
    var body: some View {
        Text(car.name)
    }
}

当您同时 select 一辆车时,这很有效。不幸的是,对于 swiftUI,我无法禁用 multi selection。如果用户同时 select 多辆汽车,然后有时返回汽车列表,我会收到错误日志:

SwiftUI encountered an issue when pushing aNavigationLink. Please file a bug.

此时,汽车列表不再有响应。它需要很少的尝试,但它最终会发生。到目前为止,我只能在 iOS 15 上复制它。我也尝试在没有 viewModel 的情况下执行此操作,但它仍然会发生。 理想情况下,我想将 NavigationLink 保留在 VStack 中,因为当用户 selects 时它会使行变暗。

我可以重现你的问题,我认为这是一个错误。 但是,将以下 NavigationLink 设置与 selectiontag 一起使用似乎对我有用。

struct ContentView: View {
    @State var cars = [Car(name: "A"), Car(name: "B"), Car(name: "C"), Car(name: "D")]
    @State private var showCar: UUID?

    var body: some View {
        NavigationView {
            LazyVStack(spacing: 30) {
                ForEach(cars) { car in
                    NavigationLink(
                         destination: CarDetailsView(car: car),
                         tag: car.id,
                         selection: $showCar,
                         label: { CarRowView(car: car) }
                     )
                }
            }
        }
    }
}

struct CarDetailsView: View {
    @Environment(\.dismiss) private var dismiss
    @State var car: Car

    var body: some View {
        Button("Back \(car.name)") {
            dismiss()
        }
    }
}

struct Car: Identifiable, Hashable {
    let id = UUID()
    var name: String
}

struct CarRowView: View {
    var car: Car
    
    var body: some View {
        Text(car.name)
    }
}