NavigationLink isActive 在 navigationBarItems(trailing:) 修饰符内不起作用

L. *_*han 1 swift swiftui

我使用的是最新版本的 Xcode (11 Beta 16) 和 macOS (10.15 Beta 6)

我正在尝试创建两个视图。从第一个视图中,您应该能够通过尾随导航栏项目导航到第二个视图,并且向后导航您应该能够使用系统生成的后退按钮(有效)和附加的尾随导航栏按钮(有一些额外的功能,比如保存数据,但这对我的问题并不重要)。

选项 1 确实有效,但如果您注释掉选项 1 并取消注释选项 2(我想要的布局),则完成按钮不会返回。

struct ContentView1: View {
    @State var show = false

    var body: some View {
        NavigationView {
            Form {
                Text("View 1")
//          Option 1 that does work
                NavigationLink(destination: ContentView2(show: $show), isActive: $show) {
                    Text("Move")
                }
            }
            .navigationBarTitle(Text("Title"))
//          Option 2 that does NOT work
//            .navigationBarItems(trailing: NavigationLink(destination: ContentView2(show: $show), isActive: $show) {
//                Text("Move")
//            })
        }
    }
}

struct ContentView2: View {
    @Binding var show: Bool

    var body: some View {
        Form {
            Text("View 2")
            Text(show.description)
        }
        .navigationBarItems(trailing: Button(action: {
            self.show = false
        }, label: {
            Text("Done")
        }))
    }
}
Run Code Online (Sandbox Code Playgroud)

任何建议如何解决这个问题?

kon*_*iki 5

选项 2 与presentationMode

struct ContentView2: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Form {
            Text("View 2")
        }
        .navigationBarItems(trailing: Button(action: {
            self.presentationMode.wrappedValue.dismiss()
        }, label: {
            Text("Done")
        }))
    }
}
Run Code Online (Sandbox Code Playgroud)