4

我可能遗漏了一些东西,但我无法让 NavigationLink 在列表中工作。
我正在使用 NavigationLink(destination, tag, selection) 我想通过点击一个按钮弹出到根视图,如您在此示例项目中所见:

import SwiftUI

struct ContentView: View {
    @State var selectedView: Int? = nil
    var colors: [String] = ["blue", "yellow", "green", "red", "black"]
    
    var body: some View {
        NavigationView {
            List{
                ForEach(colors.indices) { index in
                    NavigationLink(
                        destination: ColorDetail(selectedView: self.$selectedView, color: colors[index]),
                        tag: index,
                        selection: self.$selectedView,
                        label: {
                            Text(colors[index])
                        })
                }
            }
        }
    }
}

struct ColorDetail: View {
    
    @Binding var selectedView: Int?
    var color: String
    
    var body: some View {
        VStack {
            Text(color)
            Text("SelectedView: \(selectedView ?? 99)")
            Button("set SelectedView to nil and go back") {
                self.selectedView = nil
            }
        }
    }
}

为什么如果我将 selectedView 设置为 nil 没有任何反应?如何在点击按钮时从 ColorDetail 弹出到根视图(ContentVIew)?

只需复制此代码并尝试它,它就会构建。

4

1 回答 1

1

正如 Asperi 所说,看起来像 14.2 中的一个错误,因为它应该真的可以将其设置为 nil。但是,如果您需要一种适用于所有版本的解决方法,请尝试使用presentationMode

struct ColorDetail: View {
    
    @Binding var selectedView: Int?
    var color: String
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        VStack {
            Text(color)
            Text("SelectedView: \(selectedView ?? 99)")
            Button("set SelectedView to nil and go back") {
                self.selectedView = nil
                self.presentationMode.wrappedValue.dismiss()
            }
        }
    }
}
于 2020-12-09T12:39:16.840 回答