列表中的 NavigationLink 使用 isActive 推送错误的行

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)

  • 当然。绑定提供了 get 和 set。为每个项目生成不同的绑定。在获取时,它会检查活动链接是否等于该项目 - 如果是,则返回 true,否则返回 false。设置时,如果传入值为 true,则会设置该项目的活动链接。如果为 false,则会将活动链接(可选)设置为零。 (2认同)