【问题标题】:NavigationLink tag and selection not working as expectedNavigationLink 标记和选择未按预期工作
【发布时间】:2020-12-09 08:04:29
【问题描述】:

我可能遗漏了一些东西,但我无法让 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)?

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

【问题讨论】:

  • 另一个 14.2 缺陷。适用于 14.1。
  • 真的吗?我希望我做错了什么......

标签: swiftui ios-navigationview swiftui-14.2-defect


【解决方案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()
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多