我不明白为什么SwiftUI NavigationLink'sisActive表现得好像它有自己的状态。即使我将一个常量传递给它,后退按钮也会在按下后覆盖绑定的值。
代码:
import Foundation
import SwiftUI
struct NavigationLinkPlayground: View {
@State
var active = true
var body: some View {
NavigationView {
VStack {
Text("Navigation Link playground")
Button(action: { active.toggle() }) {
Text("Toggle")
}
Spacer()
.frame(height: 40)
FixedNavigator(active: active)
}
}
}
}
fileprivate struct FixedNavigator: View {
var active: Bool = true
var body: some View {
return VStack {
Text("Fixed navigator is active: \(active)" as String)
NavigationLink(
destination: SecondScreen(),
// this is technically a constant!
isActive: Binding(
get: { active },
set: { newActive in print("User is setting to \(newActive), but we don't let them!") }
),
label: { Text("Go to second screen") }
)
}
}
}
fileprivate struct SecondScreen: View {
var body: some View {
Text("Nothing to see here")
}
}
这是一个最小的可重现示例,我的实际意图是手动处理后退按钮按下。因此,当调用set内部时Binding,我希望能够决定何时实际进行。(所以就像基于一些验证或其他东西。)
而且我不明白发生了什么以及为什么后退按钮能够覆盖常量绑定。