Boo*_*rry 1 xcode swift swiftui
我正在尝试使用 NavigationLink 的 isActive 变量弹出回根视图控制器。
我遇到的问题是,单击列表项时使用 isActive 会推送错误的行。删除 isActive 变量,一切都会按预期工作。
以下是一些用于演示目的的示例代码:
struct ContentView: View {
@State private var activateNavigationLink: Bool = false
var exampleData = ["a", "b", "c"]
var body: some View {
NavigationView {
List(exampleData, id: \.self) { item in
NavigationLink(
destination: SecondView(item: item), isActive: $activateNavigationLink) {
Text(item)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二视角
struct SecondView: View {
var item: String
var body: some View {
Text(item)
}
}
Run Code Online (Sandbox Code Playgroud)
这让我抓狂。任何帮助将不胜感激。
jn_*_*pdx 12
因为activateNavigationLink' ' 只是Bool您代码中的 a ,如果是true,则 everyNavigationLink都会在您的List. 现在,这表现为C每次都会推送最后一个项目 ( )。
相反,您需要一些系统来存储哪个项目处于活动状态,然后将其转换为布尔绑定以供NavigationLink使用。
这是一种可能的解决方案:
struct ContentView: View {
@State private var activeNavigationLink: String? = nil
var exampleData = ["a", "b", "c"]
func bindingForItem(item: String) -> Binding<Bool> {
.init {
activeNavigationLink == item
} set: { newValue in
activeNavigationLink = newValue ? item : nil
}
}
var body: some View {
NavigationView {
List(exampleData, id: \.self) { item in
NavigationLink(
destination: SecondView(item: item), isActive: bindingForItem(item: item)) {
Text(item)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)