[英]NavigationLink in List using isActive pushes the wrong row
I'm trying to use NavigationLink's isActive variable to pop back to the root view controller.我正在尝试使用 NavigationLink 的 isActive 变量弹回根视图 controller。
The problem I'm experiencing is that using isActive pushes the wrong row when clicking on a list item.我遇到的问题是单击列表项时使用 isActive 会推送错误的行。 Remove the isActive variable and everything works as expected.
删除 isActive 变量,一切都按预期工作。
Here's some example code for demonstration purposes:下面是一些用于演示目的的示例代码:
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)
}
}
}
}
}
SecondView第二视图
struct SecondView: View {
var item: String
var body: some View {
Text(item)
}
}
This is driving me nuts.这让我发疯了。 Any help would be greatly appreciated.
任何帮助将不胜感激。
Because activateNavigationLink
is just a Bool
in your code, if it is true
, every NavigationLink
will register as active in your List
.因为
activateNavigationLink
在你的代码中只是一个Bool
,如果它是true
,每个NavigationLink
都会在你的List
中注册为活动的。 Right now, this is manifesting as the last item ( C
) getting pushed each time.现在,这表现为每次推送的最后一项(
C
)。
Instead, you'd need some system to store which item is active and then translate that to a boolean binding for the NavigationLink
to use.相反,您需要一些系统来存储哪个项目处于活动状态,然后将其转换为 boolean 绑定以供
NavigationLink
使用。
Here's one possible solution:这是一种可能的解决方案:
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)
}
}
}
}
}
You should not use activeNavigationLink on main view it should be used with cellView您不应该在主视图上使用 activeNavigationLink 它应该与 cellView 一起使用
struct ContentView: View {
var exampleData = ["a", "b", "c"]
var body: some View {
NavigationView {
List(exampleData, id: \.self) { item in
CellView(item: item)
}
}
}
}
CellView单元视图
struct CellView: View {
@State private var activateNavigationLink: Bool = false
var item: String
var body: some View {
NavigationLink(
destination: SecondView(item: item), isActive: $activateNavigationLink) {
Text(item)
}
}
}
SecondView第二视图
struct SecondView: View {
var item: String
var body: some View {
Text(item)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.