【发布时间】:2022-11-06 10:15:35
【问题描述】:
如何通过新的 .navigationDestination(for: , destination: ) 传递绑定?
import SwiftUI
enum TestEnum: String, Hashable, CaseIterable {
case first, second, third
}
struct ContentView: View {
@State private var test: TestEnum = .first
var body: some View {
NavigationStack {
VStack {
NavigationLink(value: test, label: {
Text(test.rawValue)
})
}
// This does not work, as it won't allow me to use $caze
.navigationDestination(for: TestEnum.self, destination: { caze in
SecondView(test: $caze)
})
}
}
}
struct SecondView: View {
@Environment(\.presentationMode) var presentationMode
@Binding var test: TestEnum
var body: some View {
ForEach(TestEnum.allCases, id: \.self) { caze in
Button(action: {
test = caze
presentationMode.wrappedValue.dismiss()
}, label: {
Text(caze.rawValue)
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
在 SwiftUI 3.0 中,我只需使用:
NavigationLink(destination: SecondView(test: $test), label: {
Text(test.rawValue)
})
这仍然是正确的方法吗,因为我们还不能通过绑定?
对使用 EnvironmentObject 和传递索引等复杂的解决方法并不真正感兴趣,因为 SwiftUI 3.0 方法可以正常工作。
但是,如果有通过 .navigationDestination(for: , destination: ) 传递绑定的正确方法,我会很乐意使用它。
【问题讨论】:
-
我认为将
NavigationLink(destination: SecondView(test: $test), label: { Text(test.rawValue) })与NavigationStack一起使用而不是navigationDestination并没有错。NavigationView已弃用,但NavigationLink(destination: ..)已弃用 -
没有“正确”的方式不是您现在使用的方式。
Binding不是Hashable
标签: swift swiftui swiftui-navigationlink swiftui-navigationstack