【发布时间】:2021-07-05 13:23:26
【问题描述】:
下面的简单导航演示演示了我的问题的一个示例:
-
NavigationView中的 SwiftUI 列表填充了来自数据模型Model的数据。 - 可以选择列表项,并且 NavigationView 正在链接右侧的另一个视图(此处使用
destination演示) - 可以从模型中清除数据 - SwiftUI 列表为空
- 模型数据可以在以后的某个时间点用新数据填充
import SwiftUI
// Data model
class Model: ObservableObject {
// Example data
@Published var example: [String] = ["Data 1", "Data 2", "Data 3"]
@Published var selected: String?
}
// View
struct ContentView: View {
@ObservedObject var data: Model = Model()
var body: some View {
VStack {
// button to empty data set
Button(action: {
data.selected = nil
data.example.removeAll()
}) {
Text("Empty Example data")
}
NavigationView {
// data list
List {
ForEach(data.example, id: \.self) { element in
// navigation to "destination"
NavigationLink(destination: destination(element: element), tag: element, selection: $data.selected) {
Text(element)
}
}
}
// default view when nothing is selected
Text("Nothing selected")
}
}
}
func destination(element: String) -> some View {
return Text("\(element) selected")
}
}
当我单击“空示例数据”按钮时会发生什么,列表将被正确清除。但是,选择是持久的,当没有选择任何内容时,NavigationView 不会跳回默认视图:
我希望视图 Text("Nothing selected") 正在加载。
我是否忽略了一些重要的事情?
【问题讨论】: